This blog post is about type assertions in TypeScript, which are related to type casts in other languages and performed via the as operator.


Table of contents:

  • Type assertions
    • Alternative syntax for type assertions
    • Example: asserting an interface
    • Example: asserting an index signature
  • Constructs related to type assertions
    • Non-nullish assertion operator (postfix !)
    • Definite assignment assertions

Type assertions

A type assertion lets us override a static type that TypeScript has computed for a storage location. That is useful for working around limitations of the type system.

Type assertions are related to type casts in other languages, but they don’t throw exceptions and don’t do anything at runtime (they do perform a few minimal checks statically).

const data: object = ['a', 'b', 'c']; // (A)

// @ts-ignore: Property 'length' does not exist on type 'object'.
data.length; // (B)

assert.equal(
  (data as Array<string>).length, 3); // (C)
  • In line A, we widen the type of the Array to object.
  • In line B, we see that this type doesn’t let us access any properties.
  • In line C, we use a type assertion (the operator as) to tell TypeScript that data is an Array. Now we can access property .length.

#typescript #javascript

Type Assertions in TypeScript
2.20 GEEK