Mastering Type Casting in TypeScript: A Complete Guide

Robin
Updated on July 9, 2023

Sometimes TypeScript can't guess the current type of an element. But as a developer, you know the correct type and you want to tell TypeScript about that. In this situation, you can TypeScript projects.

Type casting is an essential feature of TypeScript that helps to explicitly convert a value from one type to another. There are 2 main methods of typecasting in TypeScript that is using the as keyword and the angle bracket <> syntax.

In this post, we will explore typecasting in TypeScript in depth. By the end of this guide, you'll have a solid understanding of this topic and will be able to use it comfortably in your future TypeScript projects.

Why Do You Need Type Casting?

As you already know, we use typecasting to mention the correct type of a value. Because when TypeScript doesn't understand the actual type, it uses any or a generic type for a value.

Different types of values have different types of features. When TypeScript is not certain about the type of a value, it will not be able to check which properties and methods you can use on that value.

          const username = document.querySelector('input')!
// Type of username variable is HTMLInputElement
        

For example, you have an <input> field in your HTML document and you want to select it. Here, I am using querySelector() method to select an element for the DOM with the tag name.

In this case, TypeScript easily sets the type of this username variable as HTMLInputElement because I am using the tag name. But what will happen if I select this element using the id value?

Note: I am using the exclamation point (!) to tell TypeScript that this element is not null.

          const username = document.getElementById('username')!
// Type of username variable is HTMLElement

console.log(username.value)    // Will throw an error
        

Here, I am selecting the same <input> element using the getElementById() method. As I am not using any tag name, TypeScript has no idea what type of element I am selecting.

That's why this time, it sets the HTMLElement as the type of this username variable. TypeScript will not allow you to access the value property on this variable. Because the value property is only available for the HTMLInputElement type.

In this situation, you can use typecasting to tell TypeScript that this element is HTMLInputElement not a generic HTMLElement type.

Also Read: Best Setup to Use TypeScript with Node.js and Express Project


TypeScript Type Casting with the "as" Keyword

One of the simple and cleaner ways for you to perform typecasting in TypeScript is by using the as keyword. Let's see how to cast the above input element to its correct type using this as keyword.

          const username = document.getElementById('username') as HTMLInputElement

console.log(username.value)    // Will not throw an error
        

You have to add the as keyword followed by the type after the value that you want to cast. When you use typecasting, you don't need to mention the exclamation point. TypeScript will understand that this element won't be null because of this casting.

What if there is a chance that the element can be null and you want to check before using it in your code? Fortunately, there is a way to do this.

          const username = document.getElementById('username')

if (username) {
    const value = (username as HTMLInputElement).value
    console.log(value)
}
        

Here I am using the if statement to confirm that username variable is not null. Then you need to put the casting in between the Parentheses "()". Now you can access the value property from this element.

Also Read: Mastering Type Guards in TypeScript: Making Your Code Safer


TypeScript Type Casting with Angle Bracket "<>" Syntax

The angle bracket <> syntax is another way to carry out typecasting in TypeScript. In this syntax, you have to define the type in between the angel brackets and put the whole thing before the value that you want to cast.

          const username = <HTMLInputElement>document.getElementById('username')

console.log(username.value)    // Will not throw an error
        

Here I am casting my input element using the angle bracket syntax. It means that this element has all the properties and methods of an HTML input element.

Note: This angle bracket syntax for casting will not work in TSX especially when you are using React.


Real-World Example of Type Casting

So far you have seen how to use typecasting while selecting HTML elements. But it's not like you will only use it for casting HTML elements. You can use this feature in many ways.

Let's see a different example where you will see a use case of typecasting.

          interface User {
    id: number
    email: string
    username: string
    address: string
}

const getData = async () => {
    const res = await fetch('https://example.com/users/1')

    const user = await res.json()

    return user as User
}

getData().then((data) => {
    console.log(data.email)
})
        

Here I have an interface called User that I will use as a type. I am fetching data from an API using the fetch() method. When we get data from an API, TypeScript has no idea what type of data we are getting. That's why it sets any as the type of this user object.

When we use any type for an object, TypeScript can't provide autocomplete or suggestions for its properties and methods. As a developer, you can use typecasting to define the type of this user object.

I am using the as keyword to cast the object as the User interface to ensure that it matches the shape of this interface. Now when you try to access the data, TypeScript will know what properties are present inside this user object.

Also Read: TypeScript Function Overloading: Learn Best Ways to Use It


Conclusion

Type casting in TypeScript allows you to handle data types more effectively, catch errors early, and make your code more readable and maintainable. By understanding the different techniques, you can write more efficient and reliable code.

You have seen 2 methods for typecasting in TypeScript. Both of them will do the same thing but it's better to use one technique throughout the whole application. It will maintain the consistency of your TypeScript code.

Related Posts