Type Casting in TypeScript: What It Is and How to Get Started

10 May 2023 Balmiki Mandal 0 Typescript

Type Casting in TypeScript

TypeScript is a highly versatile language, offering both static and dynamic type checking. However, when it comes to casting types, there is no one-size-fits-all approach. In this article, we'll look at different ways to cast types in TypeScript.

Type Assertion

Type assertion is the process of asserting a value to be of a certain type, without actually performing any type checking. It's also known as type casting or type conversion. Type assertion can be done in two ways: by using angle brackets (<>) or the as-syntax.

Angle bracket syntax looks like this:

let someValue: any = "this is a string";
let strLength: number = (< string > someValue).length;

The as syntax looks like this:

 let someValue: any = "this is a string";
 let strLength: number = (someValue as string).length; 

Type Aliasing

Type Aliasing allows you to create a new name for an existing type. This is useful when you want to create a more descriptive type name that can be used in multiple locations. Type Aliasing is declared using the type keyword, and takes the following syntax:

 type  = ;

For example:

 type StringOrNumber = string | number; 
 let myVar: StringOrNumber = "Hello World!"; 

In this example, myVar is declared as a StringOrNumber, which we have aliased to the string | number type. This allows us to use the descriptive type name in multiple places.

Union Types

Union types are a combination of two or more types, which allows us to specify either type when defining a variable. For example:

 let myVar: number | string = "123";

In this example, myVar is declared as a union type of number and string. This means that it can accept either a number or string value.

Conclusion

Type casting in TypeScript is a powerful tool when working with data in a typed language. Depending on your needs, you can choose from several different approaches. Whether it’s type assertions, type aliases or union types, understanding how to cast types in TypeScript will help you write better, more reliable code.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.