Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make some properties optional in a TypeScript type

Tags:

typescript

If I have a type with all required properties, how can I define another type with the same properties where some of it's properties are still required but the rest are optional?

For example I want a new type derived from SomeType where prop1 and prop2 are required but the rest are optional:

interface SomeType {
    prop1;
    prop2;
    prop3;
    ...
    propn;
}

interface NewType {
    prop1;
    prop2;
    prop3?;
    ...
    propn?;
}
like image 567
spb Avatar asked Oct 08 '18 13:10

spb


People also ask

How do I make properties optional in TypeScript?

Use the Partial utility type to make all of the properties in a type optional, e.g. const emp: Partial<Employee> = {}; . The Partial utility type constructs a new type with all properties of the provided type set to optional. Copied!

How do you define optional in TypeScript?

In typescript, the optional parameter is defined as a parameter that can be made optional while passing the values when the function is called and the values that are passed when the function is called is printed with no errors but when the functions have declared the parameters that are ending with “?” are marked as ...

How do I make my interface properties optional?

The declaration of the interface is a place to make some properties optional. You can achieve that with a question mark next to the properties names.

How do you declare an object member as optional in TypeScript?

Inside the brackets, we can define the name of the property followed by the ? (question mark) and : (colon) symbol, and finally the type of property to make it an optional object property in TypeScript. To end the type declaration we can either use the ; symbol (semi-colon) or the , symbol (comma).


1 Answers

You can use combination of Partial and Pick to make all properties partial and then pick only some that are required:

interface SomeType {
    prop1: string;
    prop2: string;
    prop3: string;
    propn: string;
}

type OptionalExceptFor<T, TRequired extends keyof T> = Partial<T> & Pick<T, TRequired>

type NewType = OptionalExceptFor<SomeType, 'prop1' | 'prop2'>

let o : NewType = {
    prop1: "",
    prop2: ""
}
like image 99
Titian Cernicova-Dragomir Avatar answered Oct 11 '22 09:10

Titian Cernicova-Dragomir