Posts > TS Basic: Type Assertion

TS Basic: Type Assertion

Sometimes you will have information about the type of value that TS can’t know about. Type assertions are used to explicitly specify the type of a value when the TS compiler is unable to infer it automatically.

Two ways to perform type assertion

1. Angle Bracket Syntax <>

  • older form of type assertion
  • you use brackets <> to specify the target type
let someValue: any = 'Hello';
let strLength: number = (<string>someValue).length

2. “as” syntax

  • newer form of assertion
  • use the as keyword to specify the target
let someValue: any = 'Hello';
let strLength: number = (someValue as string).length
👌They are simply a way to provide hints to the TS compiler for type checking during the compilation process

Tags 🏷