An Introduction To Type Assertions In TypeScript

10 May 2023 Balmiki Mandal 0 Typescript

What is Type Assertion in TypeScript?

Type Assertion is a way of giving hints to the compiler that, when executing code, involves trusting the programmer’s judgement over the compiler’s. Type Assertion helps increase type safety in programs by providing more accurate typing information to the compiler.

In TypeScript, type assertion is done by using angle brackets (<>) and the as keyword. Angle brackets (<>) indicate the beginning of a type-assertion operator and the as keyword helps specify the type of the expression following it.

Advantages of Type Assertion

  • It helps increase type safety and accuracy of the program.
  • It can help with refactoring legacy code.
  • It makes for cleaner and more readable code.

Example of Type Assertion

The following example shows how type assertion can be used to clarify the type of an expression.

	let age: any = "18";
	let myAge = age as number;
	myAge++;

In the example above, we are using type assertion to make sure the age variable is treated as a number instead of a string. This ensures that the code will execute correctly, even though the age variable was originally declared as type any.

Conclusion

Type Assertion is a great way to provide more accurate typing information to the compiler, and helps increase type safety in our programs. It also makes for cleaner and more readable code. We can use Type Assertion in TypeScript to improve our programs and make sure that they run correctly.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.