Is it possible to generate a strict type from a partial type?

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, /* and other props */ } type PersonStrict = { name: string, age: number, /* and other props */ } 

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; 
+5
source share
1 answer

I found a way to do this.

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

Brackets attached to keyof T are required.

Without these parentheses, age is still optional.

+2
source

Source: https://habr.com/ru/post/1260982/


All Articles