【发布时间】:2021-06-11 02:48:42
【问题描述】:
我正在尝试构建某种“流畅的 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 的限制?
是否有任何变通方法可以让方法链与泛型推理一起工作?
【问题讨论】:
标签: typescript typescript-generics