小编Vik*_*r W的帖子

Typescript 推断派生类中的函数参数

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

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

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

当前执行此操作的正确方法如下:

open(data: string) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

open(data: number) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

types inference type-inference typescript

5
推荐指数
1
解决办法
698
查看次数

标签 统计

inference ×1

type-inference ×1

types ×1

typescript ×1