TypeScript Casting
There are times when working with types where it's necessary to override the type of a variable, such as when incorrect types are provided by a library.
Casting is the process of overriding a type.
const x: unknown = 'Typescript';
console.log((x as string).length);
Casting doesn't actually change the type of the data within the variable
let x: unknown = 4;
console.log((x as string).length);
// Output undefined since numbers don't have a length
TypeScript will still attempt to type-check casts to prevent casts that don't seem correct
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
Force casting
To override type errors that TypeScript may throw when casting, first cast to unknown
, then to the target type.
console.log(((4 as unknown) as string).length)
// 4 is not actually a string so this will return undefined