码迷,mamicode.com
首页 > 其他好文 > 详细

TypeScript - 元组

时间:2019-05-17 18:01:57      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:fixed   index   12c   元组   ssi   param   bool   text   对象   

数组合并了相同类型的对象,而元组(Tuple)合并了不同类型的对象。定义一对值分别为 stringnumber 的元组:

let xcatliu: [string, number] = [Xcat Liu, 25];

当赋值或访问一个已知索引的元素时,会得到正确的类型:

let xcatliu: [string, number];
xcatliu[0] = Xcat Liu;
xcatliu[1] = 25;
 
xcatliu[0].slice(1);
xcatliu[1].toFixed(2);

也可以只赋值其中一项:

let xcatliu: [string, number];
xcatliu[0] = Xcat Liu;

但是当直接对元组类型的变量进行初始化或者赋值的时候,需要提供所有元组类型中指定的项。

let xcatliu: [string, number];
xcatliu = [Xcat Liu, 25];
 
let xcatliu: [string, number] = [Xcat Liu];
 
// index.ts(1,5): error TS2322: Type ‘[string]‘ is not assignable to type ‘[string, number]‘.
// Property ‘1‘ is missing in type ‘[string]‘.
 
let xcatliu: [string, number];
xcatliu = [Xcat Liu];
xcatliu[1] = 25;
 
// index.ts(2,1): error TS2322: Type ‘[string]‘ is not assignable to type ‘[string, number]‘.
// Property ‘1‘ is missing in type ‘[string]‘.

当添加越界的元素时,它的类型会被限制为元组中每个类型的联合类型:

let xcatliu: [string, number];
xcatliu = [Xcat Liu, 25];
xcatliu.push(http://xcatliu.com/);
xcatliu.push(true);
 
// index.ts(4,14): error TS2345: Argument of type ‘boolean‘ is not assignable to parameter of type ‘string | number‘.
// Type ‘boolean‘ is not assignable to type ‘number‘.

 

TypeScript - 元组

标签:fixed   index   12c   元组   ssi   param   bool   text   对象   

原文地址:https://www.cnblogs.com/xjy20170907/p/10882797.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!