...

Web Technologies - TypeScript

Back to Course

Lesson Description


Lession - #1451 TypeScript Casting


There are times when working with types wherever it's a necessity to override the sort of a variable, such as once incorrect types are provided by a library.

Casting is the method of overriding a type.

Casting with as
A straightforward way to cast a variable is using the as keyword, which will directly change the sort of the given variable.

Example

let x: unknown = 'hello';
console.log((x as string>
.length>
;


Casting with
Using works the same as casting with as.

Example

let x: unknown = 'hello';
console.log((x>
.length>
;


Force casting
To override type errors that typescript could throw when casting, 1st cast to unknown, then to the target type.

Example

let x = 'hello';
console.log(((x as unknown>
as number>
.length>
; // x isn't actually a number thus this will return undefined


Online compiler