TS学习随笔(四)-数组的类型
typescript 字符串转数组少侠们,今天我们继续来搞⼀搞TS
今天我们要来看⼀看TS中数组的定义是个什么⿁样⼦
数组的类型:
在 TypeScript 中,数组类型有多种定义⽅式,⽐较灵活。下⾯我们来看看有哪些定义⽅法
「类型 + ⽅括号」表⽰法:
最简单的⽅法是使⽤「类型 + ⽅括号」来表⽰数组:
let tsArray: number[] = [1,1,2,3,4]
数组中的项中不允许出现其他类型
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类型的参数,所以报错了。
数组泛型:
也可以使⽤数组泛型(Array Generic) Array<elemType> 来表⽰数组:
let fibonacci: Array<number> = [1, 1, 2, 3, 5];
关于泛型,⼤家可以先仔细学习⼀下,后⾯我们也会学到
⽤接⼝表⽰数组:
interface NumberArray {
[index:number]: number;
}
let fibonacci: NumberArray = [1,1,2,3,4]
NumberArray表⽰:只要index的类型是number,那么值的类型必须是number。
any 在数组中的应⽤
⼀个⽐较常见的做法是,⽤ any 表⽰数组中允许出现任意类型:
let list: any[] = ['Xcat Liu', 25, { website: 'xcatliu' }];
类数组(特别注意)
类数组(Array-like Object)不是数组类型,⽐如 arguments:
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;
}
好了,以上就是TS⾥⾯的数组类型
参考⽂章:github/xcatliu/typescript-tutorial/blob/master/basics/type-of-array.md
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论