5
我们可以从生成严格的类型如下图所示(从打字稿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 }
其实我是想
我需要以下2种类型,但不希望给他们写了两次。
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;
不幸的是,这是无意的行为,将被修复。 https://github.com/Microsoft/TypeScript/issues/12791 – iwata0303