• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

typescript五ts数组类型的定义

武飞扬头像
隔壁老王seabiscuit
帮助3

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

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中的接口

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanheiigge
系列文章
更多 icon
同类精品
更多 icon
继续加载