【问题标题】:Why does method chaining in TypeScript cause generic type inference to fail?为什么 TypeScript 中的方法链接会导致泛型类型推断失败?
【发布时间】: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


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 嗯,当然,我已经知道了,我在问为什么The call on the right-hand side cannot use the type you declared in the left.
    • 如果您已经知道(即使您没有提及),并且这是不可接受的,那么答案是“不”。
    • 我在我的问题中展示的全部观点就是这样。我不需要重申我的问题的前提。此外,“不”显然不是对“为什么”问题的回答。
    • 你没有问“为什么”的问题。你问你是否做错了什么,是否有办法让它发挥作用。两者的答案都是“不”,除了我在答案中写的。
    • @Arad 这是上述问题的正确答案。你,阿拉德,已经知道答案的事实只是表明你没有问对正确的问题。这不会改变它是您所写问题的正确答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 2019-09-17
    • 2019-10-11
    相关资源
    最近更新 更多