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

321
Views
Is there some way to do a kind of relationship between keys in an interface in Typescript?

Let me try to explain. I have the follow response interface:

interface IResponse {
  status: "success" | "error";
  content: IMySuccessResponse | string;
}

Is there any way to make Typescript understand that when the status for equal to "success" the only possible value of content will be "IMySuccessResponse", and when the status for equal to "error" the only possible value of content will be a string?

I tried something like that:

interface IResponse {
  response: {
    status: "success";
    content: IMySuccessResponse ;
  } | {
    status: "error";
    content: string;
  }
}

But the Typescript kept on understanding that both values of content are possible regardless of status value.

EDIT =========================================================

OMG, the issue was in the destructuring. Somehow the destructuring was messing up the Typescript, so without the destructure it's worked.

enter image description here

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

0

As TS only does checks at compile-time, you have to make it know what the value of status is.

The following works for me:

type IMySuccessResponse = { hello: string }

interface IResponse {
  response: {
    status: "success";
    content: IMySuccessResponse ;
  } | {
    status: "error";
    content: string;
  }
}

const response: IResponse = /* ... */;

if (response.response.status === "success") {
  // inside this scope, the type of `content` is `IMySuccessResponse`.
  console.log(response.response.content.hello);
} else {
  // in this scope, `content` is a string.
  console.log(response.response.content);
  console.log(response.response.content.hello); // this, TS complains that `content` is a string
}

If you check for the value of content, within the scope of that check, TS will be clever enough to know what type it could be.

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!