Type Assertion
Pada TypeScript kita dapat melakukan type assertion dengan menggunakan tanda as
atau <type>
. Type assertion digunakan untuk mengubah tipe data dari suatu variabel.
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
Type assertion tidak dapat digunakan untuk mengubah tipe data yang tidak kompatibel.
let someValue: any = "this is a string";
let strLength: number = (<number>someValue).length;
let someValue: any = "this is a string";
let strLength: number = (someValue as number).length;