Typescript 继承,其中 IntelliSense 中的数据类型是任何而不是预期的数字

Typescript inheritance where datatypes in IntelliSense is any instead of expected number

我在 Typescript 中有一个很小的代码实现,其中我有一个 class 实现接口或扩展 class。

interface ITest {
    run(id: number): void
}

abstract class Test implements ITest {

    abstract run(id);
}

class TestExtension extends Test
{
    constructor() {
        super();
    }

    public run(id) { }
}

class TestImplementation implements ITest {
    constructor() {

    }

    public run(id) { }
}

两者都显示错误的 Intellisense,我希望 id 的类型为 'number':

(method) TestExtension.run(id: any): void
(method) TestImplementation.run(id: any): void

我当然可以将方法实现设置为 public(id: number) { } 但我不明白为什么我必须这样做。

请问有没有大佬解惑一下?

你对implements ITest的理解有点不对。 TypeScript 接口实现不像其他语言,它是纯粹的编译时静态契约,class 的成员必须与接口定义兼容。

所以像下面这样是正确的:

let foo: number;
let bar; // inferred any 
foo = bar; 

以下也是正确的

interface IFoo {
  foo: number
}
class Foo implements IFoo {
  foo; // Inferred any
}

函数参数也是代码中的任意参数,没有显式签名

修复

明确:public run(id) { }public run(id: number) { } 如果您希望编译器为您捕获这些情况,则可选择使用 noImplicitAny 进行编译