Home > database >  Make the type of one property depending upon other properties
Make the type of one property depending upon other properties

Time:05-02

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:

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

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

CodePudding user response:

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;
}

  • Related