Let's have the following simplified example:
type AB = {
foo: "A"
bar: "A"
} | {
foo: "B"
bar: "B"
}
type Foo = AB["foo"]
function fun<F extends Foo>(foo: F, bar: Extract<AB, { foo: F }>["bar"]) {
fun2({
foo,
bar,
})
}
function fun2(ab: AB) {
}
It fails with: Argument of type '{ foo: "A" | "B"; bar: "A" | "B"; }' is not assignable to parameter of type 'AB'.
How to restrict the generic type not to accept union types?
- @jcalz answers a similar question here Constraining type in Typescript generic to be one of several types. But the answer requires passing all "simple types" to a tuple type.
- @jcalz then discourages to use his solution from https://stackoverflow.com/a/55128956/121968 to convert union type to tuple type.
And then how to prevent
bar: Extract<AB, { foo: F }>["bar"]
to return union type?