Home > Software design >  Rewrite TypeScript property to be optional via type merging
Rewrite TypeScript property to be optional via type merging

Time:10-28

Is there a single way to make property of type optional via intersection for example?

I was thinking that if we have type T:

type T = {
 x: string
 y: string
 z: string
}

then:

T & { z?: string }

would rewrite z property of T to become optional. But this is not the case.

How can I achieve, so z will be optional property?

Thanks.

CodePudding user response:

You could use the Omit utility type:

Constructs a type by picking all properties from Type and then removing Keys (string literal or union of string literals).

You'd use that to construct a new type with all properties of T except for z, and then use an intersection type to "add it back" as an optional property, like this:

type TWithOptionalZ = Omit<T, 'z'> & { z?: string };

Playground link

If you want a generic way to do this for any keys in T, you could do something like this:

type MakeOptional<T, Keys extends keyof T> = Omit<T, Keys> & Partial<Pick<T, Keys>>;

type TWithOptionalZ = MakeOptional<T, 'z'>;
  • Related