ts定义数组类型_TS学习随笔(四)-数组的类型

ts定义数组类型_TS学习随笔(四)-数组的类型
少侠们,今天我们继续来搞⼀搞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'.饮料瓶提手
tzd
上例中,[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 来表⽰数组:
let fibonacci: Array = [1, 1, 2, 3, 5];
关于泛型,⼤家可以先仔细学习⼀下,后⾯我们也会学到
⽤接⼝表⽰数组:
interfaceNumberArray {
[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⾥⾯的数组类型

本文发布于:2024-09-21 17:36:39,感谢您对本站的认可!

本文链接:https://www.17tex.com/tex/2/137327.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:类型   数组   定义   出现   允许   饮料瓶   膏药
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议