一、基礎
TypeScript里,在有些沒有明確指出類型的地方,類型推論會幫助提供類型
let x = 3; // let x: number
二、最佳通用類型
計算通用類型算法會考慮所有的候選類型,并給出一個兼容所有候選類型的類型。
// demo 1
let x = [0, 1, null, 'haha']; // let x: (string | number | null)[]
// demo 2
class Rhino {
constructor() {
}
}
class Elephant {
constructor() {
}
}
class Snake {
constructor() {
}
}
let zoo = [new Rhino(), new Elephant(), new Snake()]; // let zoo: (Rhino | Elephant | Snake)[]
三、上下文類型
TypeScript類型推論也可能按照相反的方向進行。 這被叫做“按上下文歸類”。按上下文歸類會發生在表達式的類型與所處的位置相關時。
TypeScript類型檢查器使用Window.onmousedown函數的類型來推斷右邊函數表達式的類型。因此,就能推斷出 mouseEvent參數的類型了。
如果函數表達式不是在上下文類型的位置, mouseEvent參數的類型需要指定為any,這樣也不會報錯了。
window.onmousedown = function(mouseEvent) { // (parameter) mouseEvent: any
console.log(mouseEvent.button); //<- Error
};
注:如果上下文類型表達式包含了明確的類型信息,上下文的類型被忽略。
// test 1
window.onmousedown = function(mouseEvent: any) {
console.log(mouseEvent.button); //<- Now, no error is given
};
// test 2
interface Name {
button: string;
}
function App() {
window.onmousedown = function(mouseEvent: Name) { // TypeScript類型檢查器使用Window.onmousedown函數的類型來推斷右邊函數表達式的類型。 因此,就能推斷出 mouseEvent參數的類型了。
console.log(mouseEvent.button); //<- Error
};
// 不能將類型“(mouseEvent: Name) => void”分配給類型“((this: //GlobalEventHandlers, ev: MouseEvent) => any) & ((this: Window, ev: MouseEvent) => any)”。
// 不能將類型“(mouseEvent: Name) => void”分配給類型“(this: GlobalEventHandlers, ev: MouseEvent) => any”。
// 參數“mouseEvent”和“ev” 的類型不兼容。
// 不能將類型“MouseEvent”分配給類型“Name”。
// 屬性“button”的類型不兼容。
浙公網安備 33010602011771號