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

124
Views
Typescript overload interface attribute

Imagine I have a bunch of payload options like:

interface IOne {
  type: 'One',
  payload: {
    name: string,
    age: number
  }
}

interface ITwo {
  type: 'Two',
  payload: string
}

declare type TBoth = IOne | ITwo;

So I can receive one of the two above as parameter. I want the typescript to be able to recognize the parameters of each type when using a switch for example.

The problem I'm having is when I'm trying to Create the object.

const value = req.body?.message; // just an example
const test: TBoth = {
  type: value ? 'One' : 'Two,  // <--- Now it should autocomplete/suggest the rights parameters based on this attribute.
}

I get:

Types of property 'type' are incompatible. Type '"One" | "Two"' is not assignable to type '"Two"'.

Is it possible?

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

0

You can narrow the types of discriminated unions like this:

const doSomething = (test: TBoth) => {
  if(test.type === `One`) {
    // hover the below `test` with VSCode you will see:
    //   (parameter) test: IOne
    handleIOne(test)
  } else {
    // hover the below `test` with VSCode you will see:
    //   (parameter) test: ITwo
    handleITwo(test)
  }
}

See a live example

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!