聯合類型(Union Types),其取值能夠爲多種類型中的一種,前提是取值的類型以前定義過。javascript
// union.ts let stringAndNumber: string | number; stringAndNumber = 'ts'; stringAndNumber = 7; 複製代碼
編譯後java
// build/union.js var stringAndNumber; stringAndNumber = 'ts'; stringAndNumber = 7; 複製代碼
可見,聯合類型使用 |
來分隔每種類型。git
// unionGetLength.ts const unionGetLength = (something: string | number): number => { return something.length; } // 0.0.4/unionGetLength.ts:2:22 - error TS2339: Property 'length' does not exist on type 'string | number'. // Property 'length' does not exist on type 'number'. // 2 return something.length; 複製代碼
問題在於 number
類型沒有 length
屬性。github
觸類旁通:換個共有的屬性
toString()
試試typescript
// unionToString.ts const unionToString = (something: string | number): string => { return something.toString(); } 複製代碼
編譯後markdown
// build/unionToString.js var unionToString = function (something) { return something.toString(); }; 複製代碼
// unionInference.ts let unionInference: string | number; unionInference = 'ts'; console.log('unionInference string length: ', unionInference.length); unionInference = 18; // 永遠活在那 18 歲 console.log('unionInference number length: ', unionInference.length); // 0.0.4/unionInference.ts:6:62 - error TS2339: Property 'length' does not exist on type 'number'. // 6 console.log('unionInference number length: ', unionInference.length); 複製代碼
上面例子中,第 2 行(基於這個文件 unionInference.ts
)unionInference
(由於 ts
)被推斷爲 string
,因此訪問 length
屬性沒有問題;同理,第 6 行(由於 18
)被推斷爲 number
,訪問 length
天然就報錯了。oop
本次代碼 Githubpost