TypeScript Notes – Type assertions

Type assertions are a way to tell the compiler “trust me, I know what I’m doing.” A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data. It has no runtime impact, and is used purely by the compiler. TypeScript assumes that you, the programmer, have performed any special checks that you need.

1. Way


let someValue: any = "this is a string";

let strLength: number = (<string>someValue).length;

2. Way

let someValue: any = "this is a string";

let strLength: number = (someValue as string).length;

Resource: TypeScript Handbook

#type-assertions, #typescript