The Slicer The Slicer - 1 year ago 154
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 };

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
, the assigned value
{ value: val }
is of type
should be valid.

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download