typescript - 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 类型的参数在这里无济于事。
解决方案
推荐阅读
- javascript - 将嵌套数组中的对象数组分组并将其总数添加到新数组中
- c# - 在 webapi .net core 3.1 上添加 app.useauthentication 时 Cors 失败
- apache-poi - Apache POI Excelsheet 到 pdf 文件
- git - 如何解决 GitHub 和 VisualStudio 上的烂摊子
- java - 如果我使用 STS 使用 java 8,那么 java 中 List.of() 的替代方法是什么
- asp.net-core-webapi - 并行文件下载 asp.net core
- abp - Abp vNext Rowaction 下拉按钮文本
- jenkins - TriggerRemoteJob - 连接到远程服务器失败
- parquet - 增量加载的 parquet 文件如何提高性能?
- c++ - 如何使用 QOpenGLWidget 实现近乎恒定的 FPS?