工具类
# Partial 转换为可选
Partial<T>
将所有属性转换为可选
export interface UserModel {
name: string;
age?: number;
sex: number;
}
type JUserModel = Partial<UserModel>
// =
type JUserModel = {
name?: string | undefined;
age?: number | undefined;
sex?: number | undefined;
}
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
# Required 转换为必选
Required<T>
将所有属性转换为必选
type JUserModel2 = Required<UserModel>
// =
type JUserModel2 = {
name: string;
age: number;
sex: number;
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# Record 构造类型
Record<K,T>
,构造一个类型,K看作key, V看作value
type TodoProperty = 'title' | 'description';
type Todo = Record<TodoProperty, string>;
// =
type Todo = {
title: string;
description: string;
}
interface IGirl {
name: string;
age: number;
}
type allGirls = Record<string, IGirl>
// =
interface allGirls{
[key: string]: IGirl
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Pick 选出需要属性
Pick<T,K>
,选出需要的属性,构成新的类型
interface Todo {
title: string;
description: string;
done: boolean;
}
type TodoBase = Pick<Todo, "title" | "done">;
// =
type TodoBase = {
title: string;
done: boolean;
}
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
# Omit 去掉某些属性
Omit<T,K>
,去掉某些属性,构成新类型
interface Todo {
title: string;
description: string;
done: boolean;
}
type TodoBase = Omit<Todo, "title" | "done">;
// =
type TodoBase = {
description: string;
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
编辑 (opens new window)
上次更新: 2022/06/19
← 类型 tsconfig详解→