0

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'.

TS playground

  1. How to restrict the generic type not to accept union types?

  2. And then how to prevent bar: Extract<AB, { foo: F }>["bar"] to return union type?

    • fun<F extends "A"> will fail with Argument of type '{ foo: F; bar: "A" | "B"; }' is not assignable to parameter of type 'AB'.

      (Btw. why foo: F and not just foo: "A" ?)

    • But bar: Extract<AB, { foo: "A" }>["bar"] will work.

TN.
  • 18,874
  • 30
  • 99
  • 157

0 Answers0