HomeToolsAbout a20k

Basic Typing

Type Annotation :

Declaring a variable with type as string

let myStr: string;

Assertion/Casting

What is Assertion

Telling the TypeScript compiler that you know more about the type of a value than it does

Type assertions do not perform any runtime checks and are purely a way to satisfy the compiler

Casting: as or <>

Type of myStr is determine by type assertion as there is no explicit type defined prior

  • myStr could be something passed dynamically as a function parameter
let strLength: number = (myStr as string).length;

Variable with missing type can later be typed with casting

// untyped initialization let value: any = "Hello World"; // assertion/casting let length: number = (value as string).length;

Syntax Collision in JSX

It's important to note that the angle bracket syntax for type assertions (<type>value) can conflict with JSX syntax in TypeScript

  • To avoid such conflicts, it's recommended to use the as keyword for type assertions instead
    • as and <> are same in context of type assertion
// (discouraged) Use on the left side for assertion/casting var foo: any; var bar = <string>foo; // same as using `as` keyword to cast type var foo = bar as string;

Non-null Assertion (!)

Way of requiring that the attribute on an object should always exist

// x in param is optional function liveDangerously(x?: number | null) { // x to always exist via assertion console.log(x!.toFixed()); }
© VincentVanKoh