首页 > 解决方案 > 为什么 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 的限制?

是否有任何解决方法可以让方法链接与通用推理一起使用?

标签: typescripttypescript-generics

解决方案


右侧的调用不能使用您在左侧声明的类型。如果您改为在调用中传递泛型参数,它会起作用:

const foo = getFoo<string>().abc(...);

如果您必须实际传递一个参数如果是泛型类型,则也可能发生推断:

const foo = getFoo('foo').abc(...)

推荐阅读