Typescript接口泛型是类型检查但未推断

问题描述 投票:0回答:1

在下面的示例代码中,实现MyInterface时......

  • 如果我没有指定输入类型,则推断为any
  • 如果我指定了错误的输入类型,它会警告我这是不正确的

如果它可以检测到错误的类型,为什么它不能推断出正确的类型?

interface MyInterface<T = any> {
    myFunction(input: T): void;
}

class MyClass implements MyInterface<number> {
    // input inferred as 'any'
    myFunction(input) {}
}

class MyClass2 implements MyInterface<number> {
    // Type 'number' is not assignable to type 'string'
    myFunction(input: string) {}
}
typescript
1个回答
1
投票

这比一般看起来要复杂一些。有一个open suggestion

© www.soinside.com 2019 - 2024. All rights reserved.