0%

【049】typescript:类型别名(type)

在TypeScript中,我们可以使用 type 关键字来定义一个类型的别名,它可以为复杂的类型结构创建更具描述性和易于理解的新名字,这有助于提高代码的可读性和可维护性,类型别名常用于联合类型

基本用法

1
2
type num = number
const a: num = 1

联合类型别名(使用最多)

1
2
3
4
type info = number | string
const x: info = 2
const y: info = 'info'
const z: info = true // 报错,类型别名info并没有布尔类型对象类型别名

对象类型别名

1
2
3
4
5
6
7
8
9
type obj = {
name: string,
age: number
}
const b: obj = {
name: '老王',
age: 18
}
console.log(b) // { name: '老王', age: 18 }

函数类型别名

1
2
3
type fn = (name: string) => string
const c:fn = (name: string) => name
console.log(c('翠花')) // 翠花

元组类型

1
2
3
type arr = [ string, number ]
const data: arr = [ '老王', 18 ]
console.log(data) // [ '老王', 18 ]

复杂类型结构

使用交叉类型和联合类型来组合多个类型。

1
2
3
4
5
6
7
8
9
10
11
12
type Person = {
name: string,
age: number
} & {
sex: string
}
const person = {
name: '翠花',
age: 18,
sex: '女'
}
console.log(person) // { name: '翠花', age: 18, sex: '女' }