typescript - 为什么 TypeScript 中的方法链接会导致泛型类型推断失败?
问题描述
我正在尝试构建某种“流畅的 API”,而且我还需要使用泛型,但 TypeScript 似乎不喜欢这种组合!
考虑以下代码:
class Foo<T> {
abc(arg: T) {
return this;
}
xyz(arg: T) {
return this;
}
}
function getFoo<T>() {
return new Foo<T>();
}
// 1. Without method chaining:
let v1: Foo<string> = getFoo();
v1.abc(/* The type of the "arg" parameter here is "string", which means that the type was inferred correctly. */);
// 2. With method chaining:
let v2: Foo<string> = getFoo().abc(/* The type of the "arg" parameter here is "unknown", which obviously means the type was NOT inferred correctly. */);
我做错了什么还是这是 TypeScript 的限制?
是否有任何解决方法可以让方法链接与通用推理一起使用?
解决方案
右侧的调用不能使用您在左侧声明的类型。如果您改为在调用中传递泛型参数,它会起作用:
const foo = getFoo<string>().abc(...);
如果您必须实际传递一个参数如果是泛型类型,则也可能发生推断:
const foo = getFoo('foo').abc(...)
推荐阅读
- tensorflow2.0 - 在 u-net 中实现 unpooling 层,发生 InvalidArgumentError
- flutter - 适用于 Web 和移动设备的 Flutter 图像选择器
- javascript - 恢复HTML后如何在插入符号位置插入HTML
- javascript - 数组替换而不是连接值
- r - 基于(独占)部分匹配从数据帧中删除行到另一个数据帧
- google-chrome - Google Document Viewer 显示:服务器无法处理请求,因为它格式错误
- javascript - IE11 中的 SetProperty 与 DOM 样式属性
- python - 如何使用 Python 中的循环从单独的变量创建数组?
- atom-editor - Atom,Structure-View 安装问题
- c# - C#:serialPort 每次读取新数字