Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make the type of one property depending upon other properties

Basically a function can take either of these two types or param:

{a: string, b: number, c: SomeType}
{a: string, b: number, d: SomeOtherType}

I know I can write the type of the parameter as {a: string, b: number, c: SomeType} | {a: string, b: number, d: SomeOtherType}, but I’m trying to come up with something like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{a: string, b: number} & ({c: SomeType} | {d: SomeOtherType})

So that I don’t have to repeat the first two properties, is this possible?

>Solution :

You can define a type alias for the static properties and then use the intersection operator (&) to combine them with the optional union like this:

TS Playground

type StaticOptions = {
  a: string;
  b: number;
};

type Options = StaticOptions & (
  { c: boolean } | { d: null }
);

function fn (options: Options): void {}


Update in response to your comment:

You can define the exclusive properties as optional and never in each other’s shape for "easier" DX:

TS Playground

type StaticOptions = {
  a: string;
  b: number;
};

type Options = StaticOptions & (
  {
    c: boolean;
    d?: never;
  }
  | {
    c?: never;
    d: null;
  }
);

function fn (options: Options): void {
  const {
    a, // string
    b, // number
    c, // boolean | undefined
    d, // null | undefined
  } = options;
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading