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;
The Partial type in TypeScript is a utility type which does the opposite of Required. It sets all properties in a type to optional.
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? 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 .
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.
Use Required type.
type Person = { name: string; age?: number; }
type RequiredPerson = Required<Person>; // === { name: string, age: number }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With