[Solved] Conditional types

I was reading the TS docs but I can't seem to grasp this concept very well. I have the following interface:
interface Response {
hasErrored: boolean;
body?: string;
}
interface Response {
hasErrored: boolean;
body?: string;
}
I want to let TypeScript know that my body is always available if "hasErrored" is false instead of checking if body exists in the first place. Thank you in advance!
3 Replies
oldben
oldben2y ago
You are looking for a discriminated union type here.
type Response = {
hasErrored: false; } | {
hasErrored: true;
body: string;
}
type Response = {
hasErrored: false; } | {
hasErrored: true;
body: string;
}
sean
seanOP2y ago
Thank you so much, in two years of typescript I somewhat never had the need to use them hahaha
oldben
oldben2y ago
Happy to help!
Want results from more Discord servers?
Add your server