【发布时间】:2017-04-23 12:15:21
【问题描述】:
我们可以从下面的严格类型生成部分类型(来自 TypeScript 2.1):
type Partial<T> = {
[P in keyof T]?: T[P];
};
type Person = { name: string, age: number }
type PersonPartial = Partial<Person>; // === { name?: string, age?: number }
相反,是否可以从部分类型生成严格类型?
type Strict<T> = { ??? };
type Person = { name: string; age?: number; }
type PersonStrict = Strict<Person>; // === { name: string, age: number }
我真正想要的
我需要以下两种类型,但不想写两次。
type Person = { name: string, age?: number, /* and other props */ }
type PersonStrict = { name: string, age: number, /* and other props */ }
我找到了如下的详细解决方案,但我想知道是否有更好的方法。
type RequiredProps = { name: string, /* and other required props */ };
type OptionalProps = { age: number, /* and other optional props */ };
type Person = RequiredProps & Partial<OptionalProps>;
type PersonStrict = RequiredProps & OptionalProps;
【问题讨论】: