type
type
關(guān)鍵字用來定義一種類型
舉個例子
type Methods = 'GET' | 'POST' | 'PUT' | 'DELETE'
let method: Methods
method = 'PUT' // OK
method = 'aaa' // error
交叉類型
表示將多個類型合并為一個類型,多用在混入
function mixin <T, U>(first: T, later: U): T & U {
// let res = <T & U>{}
let res = {} as T & U
for (let id in first) {
(<any>res)[id] = (<any>first)[id];
}
for (let id in later) {
if (!(res as any).hasOwnProperty(id)) {
(<any>res)[id] = (<any>later)[id];
}
}
return res
}
聯(lián)合類型
表示變量可能的類型
let a : number | string
a = 1
a = 'test'
標識為聯(lián)合類型的變量,只能調(diào)用聯(lián)合類型共有的屬性或者方法
class Bird {
fly () {
console.log('fly')
}
eat () {
console.log('bird eat..')
}
}
class Fish {
swim () {
console.log('swim')
}
eat () {
console.log('fish eat..')
}
}
function getAnimal (): Bird|Fish {}
getAnimal().eat()
getAnimal().swim // error
類型保護
繼續(xù)上面的例子
假設(shè)我們確實要訪問非共有屬性或者方法,可以使用類型斷言
// 使用類型斷言
(getAnimal() as Fish).swim();
(getAnimal() as Bird).fly();
這樣的話我們不得不多次使用類型斷言,假若我們一旦檢查過類型,就能在之后的每個分支里清楚地知道類型的話就好了。
類型保護就可以做到,類型保護就是一些表達式,它們會在運行時檢查以確保在某個作用域里的類型。 要定義一個類型保護,我們只要簡單地定義一個函數(shù),它的返回值是一個 類型謂詞:
function isFish(pet: Fish | Bird): pet is Fish {
return (<Fish>pet).swim !== undefined;
}
pet is Fish
就是類型謂詞。 謂詞為 parameterName is Type
這種形式,parameterName
必須是來自于當前函數(shù)簽名里的一個參數(shù)名
通過類型保護,typeScript 可以推斷 if
分支的 pet
一定是 Fish
,else
分支的一定是 Bird
let pet = getAnimal()
if (isFish(pet)) {
pet.swim()
} else {
pet.fly()
}
此外也可以使用 typeof
,instanceof
做類型保護
function checkType (val: number | string) {
if (typeof val === 'number') {}
if (typeof val === 'string') {}
}
function checkInstance (val: Bird | Fish) {
if (val instanceof Bird) {}
if (val instanceof Fish) {}
}
注意, typeof
只有和基本類型(number,string,boolean,symbol
)通過 ===, !==
比較時,才會被識別為類型保護