宣告合併
如果定義了兩個相同名字的函式、介面或類別,那麼它們會合併成一個型別:
函式的合併
之前學習過,我們可以使用過載定義多個函式型別:
function reverse(x: number): number;
function reverse(x: string): string;
function reverse(x: number | string): number | string {
if (typeof x === 'number') {
return Number(x.toString().split('').reverse().join(''));
} else if (typeof x === 'string') {
return x.split('').reverse().join('');
}
}介面的合併
介面中的屬性在合併時會簡單的合併到一個介面中:
interface Alarm {
price: number;
}
interface Alarm {
weight: number;
}相當於:
注意,合併的屬性的型別必須是唯一的:
介面中方法的合併,與函式的合併一樣:
相當於:
類別的合併
類別的合併與介面的合併規則一致。
同名的類別會發生宣告衝突,無法直接合併。(原文的內容有誤,已發 Issue 要求更正)
參考
Last updated
Was this helpful?