Skip to content

Casting

Casting overrides the variable type, which you may want to do when you know more about the type than the compiler does.

Tell the compiler to treat a value as a specific type:

let input: unknown = "Hello World!";

// Can't use string methods on unknown
input.length; // Error: 'length' doesn't exist on 'unknown'

// Cast it to string
(input as string).length; // 12

Casting doesn’t change the actual value - it just tells TypeScript how to treat it:

let num: unknown = 42;
console.log((num as string).length); // undefined at runtime
// TypeScript trusts you, but the value is still a number
console.log((3 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.

Note: doesn’t work in TSX.

let a: unknown = "Hello World!";

console.log((<string>a).length); // Works.

You can force cast to any type by casting to unknown, then to the type you want. This will override any errors thrown by casting.

let a = "Hello World!";
// prettier-ignore
console.log(((a as unknown) as number).length); // a is not
// really a number so returns undefined.