2016-12-08 18 views
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; 

回答

2

我找到了解决问题的方法。附接到keyof T

type Person = { name: string, age?: number }; 
type Strict<T> = { [K in (keyof T)]: T[K] }; 
type PersonStrict = Strict<Person>; 

括号是强制性的。

没有这些括号,age仍然是可选的。

+1

不幸的是,这是无意的行为,将被修复。 https://github.com/Microsoft/TypeScript/issues/12791 – iwata0303

相关问题