0
由於打字稿2.0,你可以使用識別聯合與枚舉作爲判別像這樣:慣用打字稿枚舉識別聯合
export function getInstance(code: Enum.Type1, someParam: OtherType1): MyReturnType1;
export function getInstance(code: Enum.Type2, someParam: OtherType2): MyReturnType2;
export function getInstance(code: Enum, someParam: UnionOfOtherTypes): UnionOfReturnTypes {
switch (code) {
case Enum.Type1:
return new ReturnType1(someParam as OtherType1);
case Enum.Type2:
return new ReturnType2(someParam as OtherType2);
}
}
作爲打字稿2.3
- 是這種習慣的方法去做這個?
- 我們能否推斷someParam的類型而不投射?
- 我們是否能夠簡化類型定義,可能使用泛型,更改函數參數等,所以我們只需要定義最終函數?
- 是否有可能宣佈的功能像consts:
const getInstance =() => {};
我一直在看你的書:)謝謝!是否有可能根據參數推斷出某種歧視聯盟的返回類型?即如果代碼是類型A,我知道返回類型是類型B. – chris
是的。返回類型的聯合的所有返回語句。例如如果你在你的代碼的不同部分返回一個'string'和'number',返回類型被推斷爲'string | number' – basarat