查看: 1|回复: 0

TypeScript - 数组

[复制链接]

2

主题

0

回帖

0

积分

积极分子

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2011-2-11
发表于 2019-5-17 16:43:00 | 显示全部楼层 |阅读模式

在 TypeScript 中,数组类型有多种定义方式,比较灵活。

let fibonacci: number[] = [1, 1, 2, 3, 5];

数组的项中不允许出现其他的类型:

let fibonacci: number[] = [1, '1', 2, 3, 5];
 
// index.ts(1,5): error TS2322: Type '(number | string)[]' is not assignable to type 'number[]'.
// Type 'number | string' is not assignable to type 'number'.
// Type 'string' is not assignable to type 'number'.

上例中,[1, '1', 2, 3, 5] 的类型被推断为 (number | string)[],这是联合类型和数组的结合。数组的一些方法的参数也会根据数组在定义时约定的类型进行限制:

let fibonacci: number[] = [1, 1, 2, 3, 5];
fibonacci.push('8');
 
// index.ts(2,16): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

上例中,push 方法只允许传入 number 类型的参数,但是却传了一个 string 类型的参数,所以报错了。

接口也可以用来描述数组:
interface NumberArray {
    [index: number]: number;
}
let fibonacci: NumberArray = [1, 1, 2, 3, 5];

NumberArray 表示:只要 index 的类型是 number,那么值的类型必须是 number

any 在数组中的应用,一个比较常见的做法是,用 any 表示数组中允许出现任意类型:

let list: any[] = ['Xcat Liu', 25, { website: 'http://xcatliu.com' }];
类数组
function sum() {
    let args: number[] = arguments;
}
 
// index.ts(2,7): error TS2322: Type 'IArguments' is not assignable to type 'number[]'.
// Property 'push' is missing in type 'IArguments'.

事实上常见的类数组都有自己的接口定义,如 IArguments, NodeList, HTMLCollection 等:

function sum() {
    let args: IArguments = arguments;
}

 数组里的元素也可以是接口里定义的

app: Info[] = [];     //  这里数组的每一项需要满足{a: number, b: string}这种类型,这里定义app是一个空数组
app = [{a: 1, b: 'b'}]

interface info{   // info是一个接口
    a: number
    b: string
}

 



来源:https://www.cnblogs.com/xjy20170907/p/10882147.html
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部