# Keyof 类型运算符
keyof运算符获取对象类型,并生成其key的字符串或数字文字并集.将keyof类型与映射类型结合使用时尤其有用
keyof (A & B) 形式的类型被转换为 keyof A | keyof B.
type A = { a: string };
type B = { b: string };
type T1 = keyof (A & B); // "a" | "b"
type T2<T> = keyof (T & B); // keyof T | "b"
type T3<U> = keyof (A & U); // "a" | keyof U
type T4<T, U> = keyof (T & U); // keyof T | keyof U
type T5 = T2<A>; // "a" | "b"
type T6 = T3<B>; // "a" | "b"
type T7 = T4<A, B>; // "a" | "b"
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
type Point = { x: number; y: number };
type P = keyof Point;
1
2
3
4
2
3
4
如果该类型具有字符串或数字索引签名,则keyof将返回这些类型:
type Arrayish = { [n: number]: unknown };
type A = keyof Arrayish;
// type A = number
type Mapish = { [k: string]: boolean };
type M = keyof Mapish;
// type M = string | number
这是因为JavaScript对象键始终被强制转换为字符串,因此obj[0]始终与obj [“ 0”]相同。
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 获取对象的key
const a = 1
type Eg1 = {
readonly name: string,
age: number,
}
// T1的类型实则是name | age
type T1 = keyof Eg1
const b:T1= 'name'
class Eg2 {
private name: string;
public readonly age: number;
protected home: string;
constructor() {
this.name = ''
this.age = 10
this.home = ''
}
}
// T2实则被约束为 age
// 而name和home不是公有属性,所以不能被keyof获取到
type T2 = keyof Eg2
const c: T2 = 'age'
const c1: T2 = 'name'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30