元祖與數組結構上相似,待會你就知道了。git
// tuple.ts let tuple: [string, number]; tuple = ['pr', 30]; let tuple1_1: [string, number] = ['pr', 30]; let tuple1_2: [string, number] = ['pr']; let tuple1_3: [string, number]; tuple1_3 = ['pr', 30, 18]; // 0.0.8/tuple.ts:6:5 - error TS2741: Property '1' is missing in type '[string]' but required in type '[string, number]'. // 6 let tuple1_2: [string, number] = ['pr']; // 0.0.8/tuple.ts:9:1 - error TS2322: Type '[string, number, number]' is not assignable to type '[string, number]'. // Types of property 'length' are incompatible. // Type '3' is not assignable to type '2'. // 9 tuple1_3 = ['pr', 30, 18]; 複製代碼
經過例子,能夠發現直接對變量類型定義並賦值的時候,不能多也不能少(挺熟悉的吧)github
問:多傳確定是不可能的了,若是少傳能夠麼?typescript
本文開篇咱們不是說元祖和數組結構相似麼,試下下標賦值數組
// tuple2.ts let tuple2: [string, number]; tuple2[0] = 'pr'; let tuple2_1: [string, number]; tuple2_1[1] = 30; 複製代碼
這波操做 666。markdown
// tuple3.ts let tuple3: [string, number] = ['pr', 30]; tuple3.push(18); tuple3.push('pr 18'); tuple3.pop(); tuple3.unshift('pr is a jser'); tuple3.unshift(null); tuple3.unshift(undefined); tuple3.unshift(false); // 0.0.8/tuple3.ts:10:16 - error TS2345: Argument of type 'false' is not assignable to parameter of type 'string | number'. // 10 tuple3.unshift(false); 複製代碼
能夠發現,添加元素的類型只能是 string | number
(添加 false
報錯了),下個定論元祖添加元素的類型只能是元祖類型的聯合類型。oop
本次代碼 Githubpost