为什么方法链在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(...)

最新更新