We can generate a partial type from a string type, as shown below (from 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 }
And vice versa, is it possible to generate a strict type from a partial type?
type Strict<T> = { ??? }; type Person = { name: string; age?: number; } type PersonStrict = Strict<Person>; // === { name: string, age: number }
What i really want
I need less than two types, but I do not want to write them twice.
type Person = { name: string, age?: number, } type PersonStrict = { name: string, age: number, }
I found a detailed solution as shown below, but I want to know if there is a better way or not.
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;
source share