【问题标题】:Typescript infer function parameters in derived class派生类中的打字稿推断函数参数
【发布时间】:2018-08-31 23:13:53
【问题描述】:

我注意到,在实现泛型接口(或类)并明确说明这些泛型的类型时,不会推断子类中函数的参数类型。

interface MyInterface<T> {
    open(data: T): void
}

class MyClass implements MyInterface<string> {
    open(data) {
        // Data should be string, but is any
    }
}

目前正确的做法如下:

open(data: string) {
    ...
}

但是,这迫使我多次输入该类型,这似乎是不必要的。以下会产生错误(这是预期的):

open(data: number) {
    ...
}

任何不是字符串的类型都会出错,所以编译器不应该能够推断出该类型是字符串吗?

【问题讨论】:

标签: typescript types type-inference inference


【解决方案1】:

这是一个known issue in TypeScript,可能会在某个时候修复。

【讨论】:

    【解决方案2】:

    正如另一个答案所说,这是 TypeScript 编译器的已知问题。

    有一种方法可以提供MyInterface 的实现,将为其推断方法参数,您只需使用返回对象而不是类的函数:

    interface MyInterface<T> {
        open(data: T): void
    }
    
    
    function createMyObject(): MyInterface<string> {
        return {
            open(data) { // data type is inferred as string here
                const n = data.length;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-01
      • 2020-03-22
      • 1970-01-01
      • 2019-12-29
      • 2021-07-22
      • 2021-01-03
      • 2020-03-01
      相关资源
      最近更新 更多