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.
You can still pass types other than
true/false
, e.g.fun<never>
givesnever
, andDerived|Base
is not assignable tonever
. So you can explicitly cast return type to suppress the TS error