0

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

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 的类型为“数字”:

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

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

有人可以启发我吗?

4

1 回答 1

0

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

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

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

于 2016-07-12T07:49:59.360 回答