【问题标题】:TypeScript mapped type with required scalar properties and optional objects具有所需标量属性和可选对象的 TypeScript 映射类型
【发布时间】:2022-07-27 01:15:21
【问题描述】:
我想要一个可以修改另一种类型的 TypeScript 泛型类型,这样任何标量属性(字符串、数字、布尔值等)仍然需要,但对象类型变为可选。
例如对于这种User 类型,我希望name 和age 是必需的,但address 是可选的。
type User = {
name: string;
age: number;
address: {
street: string;
postcode: string;
};
};
【问题讨论】:
标签:
typescript
typescript-generics
mapped-types
【解决方案1】:
在写出这个问题时,我想出了答案。 StackOverflow 是不是很棒!
type ScalarTypes = string | number | boolean | Date;
type OptionalObjects<T> = {
[P in keyof T as T[P] extends ScalarTypes ? P : never]: T[P];
} & {
[P in keyof T as T[P] extends ScalarTypes ? never : P]?: T[P];
};
// this is valid
const partialUser: OptionalObjects<User> = {
name: "Me",
age: 12,
};
// this is valid
const fullUser: OptionalObjects<User> = {
name: "Me",
age: 12,
address: {
street: "My Street",
postcode: "AB123",
},
};
// @ts-expect-error this is not allowed because name and age are missing
const emptyUser: OptionalObjects<User> = {};