首页 > 解决方案 > TS2322 TS2345 但 ___ 可以用不同的约束子类型实例化

问题描述

如何处理这种烦人的新类错误?我什至没有初始化 T。我尝试了 TypeScript 4.0.8 和 4.3.5。

// error TS2322: Type 'number' is not assignable to type 'T'.
//   'number' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | number'.
function abc<T extends string | number>(): T {
    return 1;
}

// error TS2345: Argument of type 'number' is not assignable to parameter of type 'T'.
//   'number' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | number'.
function abc<T extends string | number>(cb: (t: T) => void) {
    cb(1);
}

理想情况下,类型缩小应该通过逻辑在 T 上可用。

if (...) {
   T is number
} else {
   T is string
}

更可笑。(完全匹配类型,但仍然失败。)

// error TS2322: Type 'string | number' is not assignable to type 'T'.
//   'string | number' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | number'.
//     Type 'string' is not assignable to type 'T'.
//       'string' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | number'.
function abc<T extends string | number>(): T {
    return 1 as (string | number);
}

我目前正在通过返回/回调来解决这个问题as any。缩小是在逻辑上完成的,因此在它工作时传入 T 类型的参数在这里无济于事

标签: typescript

解决方案


推荐阅读