【问题标题】:TypeScript compile error TS2322 when assigning a value of a generic type分配泛型类型的值时,TypeScript 编译错误 TS2322
【发布时间】:2016-11-19 17:56:29
【问题描述】:

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

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 }; 行产生错误:

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

但是,由于W 扩展了Wrapper&lt;T&gt;,分配的值{ value: val } 其中val 的类型为T 应该是有效的。

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

【问题讨论】:

    标签: generics typescript


    【解决方案1】:

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

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

    { value: 1 } 不能分配给 ExtendedWrapper&lt;number&gt;(属性 anotherValue 缺失)。

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

    【讨论】:

      猜你喜欢
      • 2020-11-09
      • 1970-01-01
      • 2018-06-09
      • 2017-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-10
      • 2019-02-07
      相关资源
      最近更新 更多