默認(rèn)情況下null和undefined是所有類型的子類型。 就是說(shuō)你可以把 null和undefined賦值給number類型的變量。
然而,當(dāng)你指定了--strictNullChecks標(biāo)記,null和undefined只能賦值給void和它們各自。 這能避免 很多常見(jiàn)的問(wèn)題。 也許在某處你想傳入一個(gè) string或null或undefined,你可以使用聯(lián)合類型string | null | undefined
類型斷言
類型斷言有兩種形式。
// 尖括號(hào)語(yǔ)法
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
// as 語(yǔ)法
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
在TypeScript里使用JSX時(shí),只有 as語(yǔ)法斷言是被允許的
對(duì)象解構(gòu)
const { a, b } = { a: "baz", b: 101,c:[1,2] }
console.log(a,b) // baz 101
// 創(chuàng)建剩余變量
const { a, ...c } = { a: "baz", b: 101, c: [1, 2] }
console.log(a,c) // baz {b: 101, c: Array(2)}
// 屬性重命名 ps:這里的冒號(hào)不是指示類型的 let {a, b}: {a: string, b: number} = { a: "baz", b: 101,c:[1,2] };
let { a: newName1, b: newName2 } = { a: "baz", b: 101,c:[1,2] };
console.log(newName1,newName2) // baz 101