Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

111
Views
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:

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

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!