Uses for the TypeScript ‘as’ assertion

Thursday, March 9, 2023

In TypeScript there is a as assertion. There are two reasons for this annotation.

Firstly it's a way to tell TypeScript that a value is of a certain type which differs from what is being inferred, or has already been set. Essentially, it's used to tell TypeScript "I am correct, I know more than you do!"

1let value: number;
2value = "hello" // Error
3value = "hello" as number; // Silence! TS has been told that "hello" is a number.

Generally you should not do this because this will remove the safety that TypeScript brings during development, and this will likely result in a runtime failure.

There are exceptions though, for example, while building this site, the Next.js locales is a string[] which means that trying to map ("en" | "fr")[] to this value resulted in an error. Specifying the values using the as keyword resolved this.

1// locales is string[]
2const { locales } = useRouter();
4// Assert that locales is ("en" | "fr")[]
5const links = (locales as ("en" | "fr")[]).map(...)

The second use for as is to tell TypeScript to be more specific with its types, making them as narrow as possible. Using as const makes typescript use the literal values

1// string[]
2const values1 = ["one", "two", "three"];
4// readonly ["one", "two", "three"]
5const values2 = ["one", "two", "three"] as const; 

This also has another benefit: Array and Object values become readonly, unlike normal Arrays and Objects which the content is mutable.

Other posts

Tagged with: