typescript 类型联动
enum MyEnum { A, B, C };
1
如果我想要另一种类型,即该枚举的键的联合字符串,我可以执行以下操作:
type MyEnumKeysAsStrings = keyof typeof MyEnum; // "A" | "B" | "C"
1
type Person = { age: number; name: string; alive: boolean };
type I2 = Person[keyof Person];
//type I2 = string | number | boolean
1
2
3
4
2
3
4
const RestfulMethod = {
get: 'GET',
post: 'POST',
put: 'PUT',
delete: 'DELETE'
} as const
type IRestfulMethod = typeof RestfulMethod
type TypeRestfulMethod = IRestfulMethod[keyof IRestfulMethod]
// type TypeRestfulMethod = 'GET' | 'POST' | 'PUT' | 'DELETE'
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
type Person = { age: number; name: string; alive: boolean };
type I2 = keyof Person
//type I2 = 'age' | 'name' | 'alive'
1
2
3
4
2
3
4
let obj = {
name: 'hello',
age: 18,
eat () {
return 'food'
},
link () {
return 'dog'
}
}
type methodsPick<T> = {[K in keyof T]: T[K] extends Function ? K : never}[keyof T];
// T1 = 'eat' | 'link'
type T1 = methodsPick<typeof obj>
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
# Partial
# pick
通过从 Type 中选择一组属性 Keys(字符串文字或字符串文字的联合)来构造一个类型。
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
todo;
const todo: TodoPreview
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# omit
与pick相反,通过从 Type 中选择所有属性然后删除 Keys(字符串文字或字符串文字的联合)来构造一个类型。
interface Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}
type TodoPreview = Omit<Todo, "description">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
createdAt: 1615544252770,
};
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
上次更新: 2023/06/10, 12:06:41