2

I have a function with a boolean type parameter to toggle, whether the returned type is some "base" or "derived" type. Now, in the body I always return an instance of derived type, which is certainly assignable to the base type (in the example below, I an write let val2: Base = val;, without error). However I still get the error, that Type 'Derived' is not assignable to type 'V extends true ? Derived : Base'.

interface Base {
  base: number;
}

interface Derived extends Base {
  derived: number;
}

function fun<V extends boolean>(): V extends true ? Derived : Base {
  let val: Derived = {
    base: 0,
    derived: 0
  };
  return val; // error appearing here
}

Why is that and how could I make that work?


I've already seen this post and read the article linked in the accepted answer but could not answer my question with this.

Reizo
  • 1,374
  • 12
  • 17

1 Answers1

0

You can still pass types other than true/false, e.g. fun<never> gives never, and Derived|Base is not assignable to never. So you can explicitly cast return type to suppress the TS error

function fun<V extends boolean>(): V extends true ? Derived : Base {
  let val: Derived = {
    base: 0,
    derived: 0
  };
  return val as V extends true ? Derived : Base;
}
ABOS
  • 3,723
  • 3
  • 17
  • 23
  • As far as I know using a type of `never` would be invalid in any case - that's why it's called `never`. Also, even if `V` was `never`, `V extends true` would then still be `false` causing `Base` to be the result of the conditional type. – Reizo Dec 12 '20 at 20:11
  • The thing is that "V extends true ? Derived : Base" could result in "never", and I don't get what you said about "never" is not a valid type. – ABOS Dec 12 '20 at 20:46
  • how could `V extends true ? Derived : Base` result in `never`? It's either `Derived` or `Base`. To be fair, not "valid" was not the right word indeed. I'll take that back. – Reizo Dec 12 '20 at 21:15
  • it is "never", so it is neither Derived nor Base. – ABOS Dec 12 '20 at 22:01
  • I do not see why you'd think that. Under what circumstances would `V extends true ? Derived : Base` evaluate to `never`? – Reizo Dec 13 '20 at 11:26
  • 1
    when V is never, V extends true ? Derived : Base evaluate to never – ABOS Dec 13 '20 at 12:04
  • Just tested that and turns out you're right - that seriously surprises me :o Does that mean, whenever I assign to some type parameter (or type depending on one) I need to assert its type explicitly, because it (the type parameter) _may be_ `never`? – Reizo Dec 13 '20 at 12:20
  • If you edit your answer (e. g. add that `V extends true ? Derived : Base` may resolve to `never`, if `V` is `never`), I can un-downvote and accept it. – Reizo Dec 21 '20 at 21:36