Curriculum
Course: TypeScript
Login
Text lesson

Casting with

The “Force Casting” section below explains how to override this behavior.

Casting with <>

Using <> works the same as casting with as.

Example

let x: unknown = ‘hello’;
console.log((<string>x).length);
This type of casting will not work with TSX, such as when working with React files.

Force casting

To bypass type errors that TypeScript may produce during casting, first cast the value to unknown, and then cast it to the desired type.

Example

let x = ‘hello’;
console.log(((x as unknown) as number).length); // x is not actually a number so this will return undefined