Type Assertion

A type assertion is a way to tell the compiler the type of a variable when TypeScript is unable to infer it automatically:

1
const text = "Hello, World!" as string;

It is important to be cautious with type assertions because they can potentially lead to dangerous errors. This is because type assertions override TypeScript’s type inference, and if used incorrectly, may result in assigning an incorrect type to a variable:

1
2
// 💀: "Hello, World!" is NOT "Something else!"
const text = "Hello, World!" as "Something else!";

Best Practice:

Type assertions can be particularly handy when writing test code. They enable you to test whether your TypeScript code can handle incorrect input by asserting a correct type to incorrect data. This enables you to pass the incorrect data to your code under test, which would otherwise be disallowed by TypeScript’s type system.

When you need to override TypeScript’s type inference, it is recommended to use an assertion function instead of a regular type assertion.

Video Tutorial:

Related: