This question is related, but a) I only care about string union types and b) I care about the type inference within the function body, not (only) the outside view.
Given these types + function
type A = "a_1" | "a_2"
type B = "b_1" | "b_2"
function foo<T extends A> (a: T, b: T extends "a_1" ? "b_1" : "b_2") {
}
… TypeScript neatly type checks calls of foo:
// these two error:
foo2("a_2", "b_1")
foo2("a_1", "b_2")
// these two compile
foo2("a_1", "b_1")
foo2("a_2", "b_2")
But: Within the function body, even when a
is checked, b’s infered type doesn’t follow suit:
function foo<T extends A> (a: T, b: T extends "a_1" ? "b_1" : "b_2") {
if (a == "a_1") {
let bar: "b_1" = b
// ^ fails with Type "b_1" | "b_2" is not assignable to type "b_1
}
}
Is there a way to have TypeScript recognize the link?