The Slicer The Slicer - 16 days ago 5
TypeScript Question

TypeScript compile error TS2322 when assigning a value of a generic type

I am trying to create a TypeScript function that has two type parameters, where one type parameter uses the other one:

interface Wrapper<T> {
value: T;
}

function func<T, W extends Wrapper<T>>(val: T, takesWrapper: (w: W) => void) {
const wrapper: W = { value: val };
takesWrapper(wrapper);
}

func(32, num => { console.log(Math.abs(num.value) + 10); });


The TypeScript compiler yields an error for the line
const wrapper: W = { value: val };
:

test.ts(6,11): error TS2322: Type '{ value: T; }' is not assignable to type 'W'.


However, as
W
extends
Wrapper<T>
, the assigned value
{ value: val }
where
val
is of type
T
should be valid.

Why does the TypeScript compiler yield a compile error in this case?

Answer

You're creating object that might be not assignable to W. For example:

interface ExtendedWrapper<T> extends Wrapper<T>{
    anotherValue: T;
}

{ value: 1 } is not assignable to ExtendedWrapper<number> (property anotherValue is missing).

You can overcome this using type assertion const wrapper = { value: val } as W; but keep in mind that takesWrapper function expects extended type.

Comments