上面已经做过数组内存在单个或多个类型一样的数组的类型定义,再复习下
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中的接口