分配通用类型的值时,TypeScript编译错误TS2322 [英] TypeScript compile error TS2322 when assigning a value of a generic type

查看:498
本文介绍了分配通用类型的值时,TypeScript编译错误TS2322的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个具有两个类型参数的TypeScript函数,其中一个类型参数使用另一个参数:

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

TypeScript编译器在const wrapper: W = { value: val };行产生错误:

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'.

但是,随着W扩展Wrapper<T>,分配的值{ value: val }(其中valT类型)应该是有效的.

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

在这种情况下,为什么TypeScript编译器会产生编译错误?

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

推荐答案

您正在创建的对象可能无法分配给W.例如:

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

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

{ value: 1 }无法分配给ExtendedWrapper<number>(缺少属性 otherValue ).

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

您可以使用类型断言const wrapper = { value: val } as W;克服此问题,但请记住,takesWrapper函数需要扩展类型.

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

这篇关于分配通用类型的值时,TypeScript编译错误TS2322的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆