typescript(五)ts中数组类型的定义

上面已经做过数组内存在单个或多个类型一样的数组的类型定义,再复习下

const arrA = [1, 2, 4] // 这里利用ts 的类型推断,arrA的数组类型定义为:
const arrA: number[] = [1, 2, 4]

数组中存在单个或者多个同类型的数组的类型定义还有很多,比如:

const arrC: boolean[] = [true, false]
const arrD: string[] = ['1', '3']
const arrE: void[] = [undefined, null, null]
const arrF: undefined[] = [undefined, undefined]

如果数组中存在不同类型的元素时,需要加个(),然后在里面加上类型定义,并且用 | 隔开就行

const arrG: (number | string | number[] | boolean)[] = [1, '4', true, [1, 2, 4]]

ts中元祖的使用:如果数组中的元素时不同类型,并且必须规定顺序,那么这样的数组应该应用中元组类型定义

const arrH: [string, boolean, number] = ['666', true, 666]
const arrI: [string, boolean, number][] = [['666', true, 666]]

数组中同类型的对象如何定义该数组呢?这种在项目里面经常用到

const arrJ: { one: string, two: number }[] = [
    {
        one: '666',
        two: 3
    },
    {
        one: '667',
        two: 20
    },
]

这样写类型定义实在是太麻烦了,ts为我们提供了类型别名的形式来代替。

1.数组的类型定义使用类型别名

type typeA = { unname: string, age: number }
const arrTypeA: typeA[] = [{ unname: '小刘', age: 24 }]

2.函数参数的类型定义使用类型别名

type typeB = { one: number, two: string }
function fntB2({ one, two }) {
    return one + two
}
const bResult2 = fntB2({ one: 1, two: '888' })

下一篇: typescript(六)ts中的接口

  • 6
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值