Typescript

Type Casting in TypeScript

📣 Sponsor

Sometimes, in TypeScript, something will have an unknown type where TypeScript can’t discern the specific type something should be. At it’s most basic, this can occur when a variable is simply given the type unknown. For example:

let text:unknown = "String Goes Here";

Although we can see that the type of the content above is a string, it has been given the type unknown, so TypeScript doesn’t know what type it is. As such, when we try to run methods on this that are string specific, they won’t work. Let’s say we wanted to get the length of this string, for example:

let text:unknown = "string"; let value = text.length;

How Casting works in TypeScript

The code above will actually throw an error, which is Object is of type 'unknown'.. To solve this problem, we need to use TypeScript casting. To cast something in TypeScript, we use the as keywords. For this example, we need to cast the text variable to a string, so TypeScript will let us use length:

let text:unknown = "string"; let value = (text as string).length;

Now TypeScript will case the type to string, and we can use length. The way this code is written is unlikely to happen in the real world, but it could occur if you receive an API response of unknown type, and have to conform it to a type.

Another common place this happens, is with selectors. For example, it’s pretty common to select an input, and expect to be able to find the value via the value property:

let input = document.querySelector('input'); let inputValue = input.value;

In TypeScript this throws an error, since Object is possibly 'null'.. TypeScript has a number of predefined types for query selector outputs, but we can’t write let input:HTMLInputElement = ... either, since the input is possibly null. As such, we have to cast the input to HTMLInputElement to get the value:

let input = document.querySelector('input') as HTMLInputElement; let inputValue = input.value;

Conclusion

I hope you’ve enjoyed this tutorial. TypeScript casting is necessary in some situations, especially when using querySelector. It’s a useful way to enforce certain type restrictions on outputs from APIs, or variables with unknown types.

Last Updated 1657368555933

More Tips and Tricks for Typescript

Subscribe for Weekly Dev Tips

Subscribe to our weekly newsletter, to stay up to date with our latest web development and software engineering posts via email. You can opt out at any time.

Not a valid email