Value not assignable to conditional type while assignable to each type individually

225 views Asked by At

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.

1

There are 1 answers

7
ABOS On

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;
}