HomeToolsAbout

Basic Typing

Type Annotation :

Declaring a variable with type as string.

let myStr: string;

Annotations will result in errors when the concrete defined type and compiler recognized types are mismatched.

Casting = Type Assertion

What is Type Assertion

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

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

  • as in, you can define something completely wrong via override.

as or <>

myStr could be something passed explicitly (and forcefully) as a function parameter, in below case, a string.

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()); }
AboutContact