TypeScript Type Casting
Type casting is the use of the as keyword to tell the compiler to treat a value as a given type. The cast changes only what the compiler believes about the value.
Cast unknown to string
The value holds a string but has type unknown. The cast lets the code read its length.
const data: unknown = "hello world";
const text = data as string;
console.log(text.length);An impossible cast
A number and a string do not overlap. The compiler refuses a direct cast between them.
const count: number = 42;
const text = count as string;
console.log(text);A cast that lies
The cast claims the value is a string. The runtime check shows the value is still a number.
let data: unknown = 42;
let text = data as string;
console.log(typeof text);Example
const data: unknown = ["red", "green", "blue"];
const colors = data as string[];
console.log(colors.length);
console.log(colors[0]);Key points
- The as keyword follows the value and names the target type.
- A cast from unknown to a known type is allowed.
- A cast between unrelated types is refused by the compiler.
- A cast through unknown can hide a wrong claim.
- A cast never changes the runtime value or its type.
In this example, an unknown value holds an array of strings. The cast tells the compiler to treat it as a string array. The program logs the array length and its first item.
Note
typeof reports the runtime type. It ignores every cast.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
What does a cast with as change at runtime?