元组
1,元组同样是TypeScript中新增的一种数据类型,元组的功能总的来说:就是给定长度,类型的一个数组,它可以对数组中的每一项的类型进行精确定义,值的类型和长度必须和声明的保持一致
const userArr: [string,number,boolean] = ['张三','18', true]
2,可以通过类型别名的形式,可以将一个元组应用给多个对象使用
type Person = [string,number,boolean]
const userArra: Person = ['张三',18, true]
const userArrb: Person = ['李四',19, false]
3,枚举和元组可以配合使用
enum Gender {
man = '男',
woman = '女'
}
type Person = [string,number,Gender]
const userArra: Person = ['张三',18, Gender.man]
const userArrb: Person = ['李四',19, Gender.woman]
枚举
1,在TypeScript中,枚举是新增的数据类型,它可以给数组中的每一项赋予指定的名字,它是用enum进行定义的:
enum directive {
up,
down,
left,
right,
}
2,在没有给数组中的每一项复制之前,它的每一项的默认值就是从零开始一一对应的,取出来的值就是它的那一项对应的值(方便记忆:它的每一项的默认值就等于那一项的索引),但是我们可以给它进行重新赋值
// 默认值
enum directive {
up = 0,
down = 1,
left = 2,
right = 3,
}
const direction:directive = directive.up
console.log(direction) // 0
// 重新赋值
enum directive {
up = '上',
down = '下',
left = '左',
right = '右',
}
const direction:directive = directive.up
console.log(direction) // 上