typescript utils
# 1. 类型中的可选属性改成必选属性
// 假设我们有个如下这样的一个类型Employee, 其中的name和salary是可选的;
interface Employee {
id: number;
name?: string;
salary?: number;
}
type withRequiredProperty<Type, key extends keyof Type> = Type & {
[Property in key]-?: Type[Property];
};
// 这样我们就可以将可选属性修改为必选属性了
const employee: withRequiredProperty<Employee, 'name' | 'salary'> = {
id: 1,
name: 'John',
salary: 5000
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
注:-?
语法称为映射修饰符 (opens new window),用于影响可选属性
使用typescript内置的Required
类型也可以使得所有属性都变成必选属性;
interface Employee {
id?: number;
name?: string;
salary?: number;
}
const employee = Required<Employee>{
id: 1,
name: 'John',
salary: 5000
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
编辑 (opens new window)
上次更新: 2023/12/23, 14:47:23