# ts 高阶类型
# 交叉类型
将多个类型合并为一个类型
interface A {
name: string
}
interface B {
age: string
}
type C = A & B
const user: C = {
name: '',
age: ''
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 联合类型
类型为多个类型中的一个
type A = 'a' | 'b' | 'c'
const a: A = 'a'
const b: A = 'b'
1
2
3
4
2
3
4
# 类型别名
类型的别名
type A = 'a' | 'b' // A 是联合类型 a | b 的别名
1
# 索引类型
keyof
索引类型
interface A {
a: string
b: string
}
type B = keyof A // a | b
1
2
3
4
5
6
2
3
4
5
6
# 类型约束
extends
对泛型加以约束
interface A {
a: string
b: string
}
function fn<T extends A>(args: T): T {
return args
}
fn({ a: '', b: '' })
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
const getValue: <T, U extends keyof T>(obj: T, key: U) => T[U] = (obj, key) => obj[key]
const obj = {
name: 'name',
age: 'age'
}
getValue(obj, 'name')
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 类型映射
type MyReadonly<T> = {
readonly [U in keyof T]: T[U]
}
1
2
3
2
3
# 条件类型
条件类型的语法规则和三元表达式一致,经常用于一些类型不确定的情况。
type Extract<T, U> = T extends U ? T : never
1
# 工具泛型
# Partial
Partial
将一个接口的所有属性全部设置为可选
type MyPartial<T> = {
[P in keyof T]?: T[P]
}
interface User {
name: string
age: string
}
const Tian: MyPartial<User> = {
name: 'tian'
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# Required
Required
与 Partial
相反,将接口的所有属性设置为必选
type MyRequired<T> = {
[P in keyof T]-?: T[P]
}
interface User {
name?: string
age?: string
}
const Tian: MyRequired<User> = {
name: 'tian',
age: '18'
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# Record
type MyRecord<T extends keyof any, U> = {
[P in T]: U
}
const A: MyRecord<'tian' | 'wu', { name: string; age: string }> = {
tian: { name: 'tian', age: '18' },
wu: { name: 'wu', age: '18' }
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# Pick
从接口中提取几个属性
type MyPick<T, K extends keyof T> = {
[P in K]: T[P]
}
const A: MyPick<{ name: string; age: string }, 'name'> = {
name: 'tian'
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# Exclude
Exclude
的作用与之前介绍过的 Extract
刚好相反,如果 T 中的类型在 U 不存在,则返回,否则抛弃。现在我们拿之前的两个类举例,看看 Exclude 的返回结果。
type MyExclude<T, U> = T extends U ? never : T
interface A {
a: string
b: string
c: string
}
interface B {
a: string
b: string
d: string
}
type ExcludeKeys = Exclude<keyof A, keyof B> // c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Omit
从接口中去除属性
type MyOmit<T, U extends keyof T> = Pick<T, Exclude<keyof T, U>>
const A: MyOmit<{ name: string; age: string }, 'name'> = {
age: '18'
}
1
2
3
4
5
2
3
4
5