'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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | yaken |


