typescript-tutorial icon indicating copy to clipboard operation
typescript-tutorial copied to clipboard

元组

Open xcatliu opened this issue 4 years ago • 6 comments

https://ts.xcatliu.com/advanced/tuple.html

xcatliu avatar Jun 08 '20 12:06 xcatliu

因此使用元祖可以确定元素数据类型,但不要超出范围,可以把元祖理解为固定长度,超出范围不能保证其类型。

tobemaster56 avatar Aug 10 '20 09:08 tobemaster56

那么请问,数组范型的联合类型或者没有any与元组有什么区别呢

thatgirlismylove avatar Aug 25 '20 03:08 thatgirlismylove

@thatgirlismylove 那么请问,数组范型的联合类型或者没有any与元组有什么区别呢

let tom: [string, number]; tom = ['Tom', 25]; // true tony = [25, 'Tom'] // false

bellakongqn avatar Aug 26 '20 01:08 bellakongqn

运行此代码会报错:

let tom: [string, number];
tom[0] = 'Tom';
tom[1] = 25;

tom[0].slice(1);
tom[1].toFixed(2);

xcatliu avatar Nov 12 '20 03:11 xcatliu

@xcatliu 运行此代码会报错:

let tom!: [string, number];
tom[0] = 'Tom';
tom[1] = 25;

tom[0].slice(1);
tom[1].toFixed(2);

加个强制断言就好了,编译能通过

allenlinc avatar Dec 21 '20 13:12 allenlinc

let tom!: [string, number]; tom = ['Jack',18]; tom[0] = 'Tom'; tom[1] = 25;

tom[0].slice(1); tom[1].toFixed(2);

要赋值才能用 否则报错

allenlinc avatar Dec 21 '20 13:12 allenlinc