I'm trying to write a function that will return a value of a tagged union, but I want the return type to be refined depending on the tag. For example,
type Token = {kind: "+"} | {kind: "var", text: string};
let tokens: Token[] = [{kind: "var", text: "x"}, {kind: "+"}, {kind: "var", text: "y"}];
function pullToken<Kind extends Token["kind"]>(kind: Kind): Extract<Token, {kind: Kind}> {
let token = tokens.shift();
if (typeof token === "undefined" || token.kind !== kind) {
throw "oops";
}
return token;
}
let token = pullToken("var");
console.log(token.text);
gives me the following error
TS2322: Type 'Token' is not assignable to type 'Extract<{ kind: "+"; }, { kind: Kind; }> | Extract<{ kind: "var"; text: string; }, { kind: Kind; }>'.
Type '{ kind: "+"; }' is not assignable to type 'Extract<{ kind: "+"; }, { kind: Kind; }> | Extract<{ kind: "var"; text: string; }, { kind: Kind; }>'.
Type '{ kind: "+"; }' is not assignable to type 'Extract<{ kind: "var"; text: string; }, { kind: Kind; }>'.
I expected token
to be refined by the condition in the if
statement, but it isn't. Is there a way to achieve this?