Curriculum
Course: TypeScript
Login
Text lesson

TS Casting

Casting is the process of overriding a variable’s type, often used when a library provides incorrect types.

Casting with as

A simple way to cast a variable is by using the as keyword, which directly changes the type of the variable.

Example

let x: unknown = ‘hello’;
console.log((x as string).length);

Casting doesn’t change the actual data type within the variable. For example, the following code will not work as expected because the variable x still holds a number, despite the cast.

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

TypeScript will still perform type checking on casts to prevent invalid conversions. For instance, the following will produce a type error because TypeScript recognizes that casting a string to a number is not meaningful 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.