discriminate unions based on return type

type Good = { is: true; _tag: "good" };
type Bad = { is: false; _tag: "bad" };

// I know ts can discriminate a union type
function x(y: Good | Bad) {
if (y.is) return;
// then we know _tag must be 'bad'
y._tag;
}

type Fortunate = { getIs: () => true; _tag: "good" };
type Unlucky = { getIs: () => false; _tag: "bad" };

// but I want to discriminate based off the return type
function z(yy: Fortunate | Unlucky) {
// this what I want to achieve
if (yy.getIs()) return;
// but _tag is still unknown
yy._tag;
}
type Good = { is: true; _tag: "good" };
type Bad = { is: false; _tag: "bad" };

// I know ts can discriminate a union type
function x(y: Good | Bad) {
if (y.is) return;
// then we know _tag must be 'bad'
y._tag;
}

type Fortunate = { getIs: () => true; _tag: "good" };
type Unlucky = { getIs: () => false; _tag: "bad" };

// but I want to discriminate based off the return type
function z(yy: Fortunate | Unlucky) {
// this what I want to achieve
if (yy.getIs()) return;
// but _tag is still unknown
yy._tag;
}
It doesn't seem to be a supported feature but I don't know all the advanced features of ts so I wondered if there's a way of doing this with a more advanced utility type. tyvm
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server