Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to generate strict type from partial type?

We can generate partial type from strict type like 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 }

Conversely, Is it possible to generate strict type from partial type ?

type Strict<T> = { ??? };

type Person = { name: string; age?: number; }
type PersonStrict = Strict<Person>; // === { name: string, age: number }

What I actually want

I need below 2 types, but don't 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 verbose solution like below, but I want to know 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;
like image 225
iwata0303 Avatar asked Dec 08 '16 09:12

iwata0303


People also ask

What is the use of partial in TypeScript?

The Partial type in TypeScript is a utility type which does the opposite of Required. It sets all properties in a type to optional.

What is deep partial?

Second-degree burns are injuries to the skin caused by heat, radiation, electricity, chemicals, or friction. A deep second-degree burn injures the top layer of skin (epidermis) and the tissue below the skin (dermis). This type of burn is also called a deep partial-thickness burn.

What does ?: Mean in TypeScript?

What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .

How do I compare types in TypeScript?

In Typescript, we have three ways to work with it using: typeof: the keyword helps to check values types, like boolean, string, number, etc. instanceof: the keyword to compare the object instance with a class constructor. type guards: The powerful way to check types using typescript feature language.


2 Answers

Use Required type.

type Person = { name: string; age?: number; }
type RequiredPerson = Required<Person>; // === { name: string, age: number }
like image 148
Eduard Avatar answered Sep 27 '22 20:09

Eduard


I found the way to do this.

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

Parentheses attached to keyof T are mandatory.

Without these parentheses, age is still optional.

like image 45
iwata0303 Avatar answered Sep 27 '22 20:09

iwata0303