TypeScript Casting: How to Perform Type Casting in TypeScript?

What is casting in TypeScript?

Casting in TypeScript is the process of converting a variable from one type to another.

This is often necessary when you’re certain about the type of an object but TypeScript is not.

Type casting in TypeScript is like telling the system to treat a value as a different type. It’s really handy when you’re dealing with data that can change, or when TypeScript can’t figure out the type of a value on its own.

Understanding the Implicit and Explicit Type Casting

Implicit type casting is when TypeScript changes a variable’s type on its own based on the situation. Like, if you try to add a number and a string, TypeScript will change the number into a string first.

Explicit type casting is when you tell TypeScript what type a variable should be. This is really useful because it helps you prevent mistakes related to types when you’re writing code.

How to Perform Type Casting in TypeScript?

You can change a variable’s type in two ways in TypeScrip using the word “as” or using angle brackets.

Most people use “as” because it’s clear and straightforward.

Using the “as” keyword for casting:

The “as” keyword provides a simple method to cast a variable, effectively altering TypeScript’s understanding of the variable’s type.

Here’s an example of how you can use “as” to change a variable’s type:

let sample: unknown = 'Hi, Welcome to Itsourcecode';
console.log((sample as string).length);

Output:

27

Casting using the < > (angle brackets) operator:

The <> operator can be used for type casting in a similar way to the “as” keyword.

However, this method is not compatible with TSX syntax, which is commonly used in React projects.

For instance:

let example: unknown = 'Hi, Welcome to Itsourcecode!';
let strLength: number = (<string>example).length;
console.log(strLength);

Output:

28

Overriding type errors with force casting:

When TS throws type errors during casting, you can bypass these by first casting to unknown, and then to the desired type. Here’s an example:

let example = 'hi, Welcome to Itsourcecode!';
console.log(((example as unknown) as number).length); // x is not actually a number so this will return undefined

Conclusion

In conclusion, we’ve learned about changing a variable’s type in TypeScript, also known as type casting.

We’ve seen examples and learned how it works.

We can change a variable’s type using the ‘as’ keyword or the ‘<>’ operator.

I hope that this article helps you understand TypeScript Casting.

If you have any questions or inquiries, please don’t hesitate to leave a comment below.

Leave a Comment