1.

What are type assertions in TypeScript?

Answer»

Sometimes, you as a programmer might know more about the type of a variable than TypeScript can infer. Usually, this happens when you know the type of an object is more specific than its current type. In such cases, you can tell the TypeScript compiler not to infer the type of the variable by using type assertions.

TypeScript provides TWO forms to assert the types.

let VALUE: unknown = "Foo";let len: number = (value as STRING).length;
  • <> syntax:
let value: unknown = "Foo";let len: number = (<string>value).length;

Type assertions are similar to TYPECASTING in other programming languages such as C# or Java. However, unlike those languages, there’s no runtime penalty of boxing and unboxing variables to fit the types. Type assertions simply let the TypeScript compiler know the type of the variable.  



Discussion

No Comment Found