Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript same derived type but all optional keys

Tags:

typescript

Is it possible to automatically derive this interface:

interface OverrideParamType {
  foo?: FooType
  bar?: BarType
}

from this one

interface ParamType {
  foo: FooType
  bar: BarType
}

The use is in functions ending with:

return Object.assign ( {}, baseParams, overrideParams )
like image 704
Anna B Avatar asked Dec 19 '16 15:12

Anna B


People also ask

How do you make all properties optional in TypeScript?

In the TypeScript, Partial<T> is implemented as below; it makes properties optional. type Partial<T> = { [P in keyof T]?: T[P]; }; In summary, whenever you need to make all properties optional, use the Partial<T> type.

How do I make my properties not required 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.

How do you make a key optional in TypeScript?

To make a single property in a type optional, create a utility type that takes a type and the property name as parameters and constructs a new type with the specific property marked as optional.

How would you declare an optional member of an interface in TypeScript?

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. In the above example, the pet is an optional property.


1 Answers

Since typescript 2.1 you can do:

interface ParamType {
    foo: FooType
    bar: BarType
}

type PartialParamType = Partial<ParamType>;

The definition of Partial is:

type Partial<T> = {
    [P in keyof T]?: T[P];
};

More on that in: Mapped Types

An example in playground.

Note that there's no need to define the Partial type yourself, it's part of the lib.d.ts.

like image 67
Nitzan Tomer Avatar answered Nov 16 '22 15:11

Nitzan Tomer