Skip to main content

TypeScript Casting

Sometimes you need to override the type of a variable — for example when a library gives you the wrong type.

Casting is the process of overriding a type.


Casting with as

The simplest way to cast a variable is the as keyword. It directly changes the type TypeScript uses for that variable.

Note: Casting does not change the data stored in the variable. The following code does not work as expected, because x still holds a number:

  • let x: unknown = 4;
  • console.log((x as string).length); // prints undefined since numbers don't have a length

Note: TypeScript still checks casts and rejects ones that do not look right. This line is a type error, because casting a number to a string makes no sense without converting the data:

  • console.log((4 as string).length); // Error: Conversion of type 'number' to type 'string' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

The Force casting section below shows how to override this.

Example

x is unknown, so you cannot read .length directly. Casting it to string makes the property available.

Prompt
Show a cast with the as keyword. Declare x typed unknown holding the string 'hello', then log (x as string).length so the output is 5.
Output: TypeScript file and captured output

Casting with <>

Using <> works the same as casting with as: write the target type in angle brackets before the value.

Note: This style of casting does not work in TSX files, such as React components.

Example

Prompt
Show the angle-bracket cast syntax as an alternative to as. Declare x typed unknown holding the string 'hello', then log (<string>x).length so the output is 5.
Output: TypeScript file and captured output

Force casting

To get around the type errors TypeScript raises for a cast, first cast to unknown, then cast to the target type.

Example

The string is forced to the type number and TypeScript accepts the double cast. It still checks what you do with the result, though: a number has no length property, so that line is reported as an error. If the check is skipped, the value is still a string pretending to be a number, and reading .length on it gives undefined.

Prompt
Show force casting: casting to unknown first and then to the target type. Declare x as the string 'hello', then log ((x as unknown) as number).length with a comment explaining that x is not really a number, so the printed value is undefined.
Output: TypeScript file and captured output