Type assertions
The as
keyword is used to make a type assertion that a value is of a specified type. For example, consider the example below where we assert that y
has a number
type.
Clearly, y
is not actually holding a number
value. TypeScript can detect several situations where an obviously incorrect type assertion is taking place, but it is very easy to misuse this keyword when attempting to resolve compiler errors.
One common use for the as
keyword is with the as const
syntax, which indicates that a value should be inferred as a literal type rather than a general type.
Another common use of the as
keyword is to explicitly tell the TypeScript compiler that an array value is actually a tuple.
You can also use as
to represent a value as a less specific type.