Type Assertions in TypeScript (Live Playground)
In this tutorial, we will explore type assertions in TypeScript, a way to inform the TypeScript compiler about a variable's type when you have more information than the type inference system.
What are Type Assertions?
Type assertions are a way to tell the TypeScript compiler that you are certain about a variable's type, even if the compiler cannot infer the type itself. Type assertions do not perform any runtime type checking or conversion; they are purely a compile-time construct.
Using Type Assertions
There are two syntaxes for type assertions: the angle-bracket syntax and the as
keyword syntax.
Angle-Bracket Syntax
let someValue: unknown = 'this is a string';
let strLength: number = (<string>someValue).length;
In this example, we use angle brackets to assert that someValue
is of type string
. This allows us to access the length
property without any type errors.
as
Keyword Syntax
let someValue: unknown = 'this is a string';
let strLength: number = (someValue as string).length;
In this example, we use the as
keyword to assert that someValue
is of type string
. This syntax is preferred when using JSX, as the angle-bracket syntax can cause conflicts with JSX tags.
When to Use Type Assertions
Type assertions should be used sparingly and only when you are confident about the variable's type. Overusing type assertions can lead to runtime errors, as the TypeScript compiler assumes that you know what you are doing.
Conclusion
In this tutorial, we have explored type assertions in TypeScript, a way to inform the TypeScript compiler about a variable's type when you have more information than the type inference system. As you continue learning TypeScript, make sure to use type assertions judiciously to avoid potential runtime errors.