如果 属性 初始化为 null,TypeScript 接口不会导致错误

TypeScript interface does not result in an error if property is initialized as null

如您所见,年龄是一个数字,如果我尝试将其初始化为数字以外的其他内容,它会相应地出错。但是,如果我将它初始化为 null 并在以后设置它,我不会从 doSomething 将它视为一个对象时得到任何错误。

TypeScript 不应该能够在尝试在 this.age 上设置 someProperty 时给出错误,这是一个数字吗?如果不是,为什么?我是否需要做一些额外的事情来告诉 TypeScript this.age 是一个数字?

interface MyServiceInterface {
  age: number;
  doSomething () : void;
}

function myService () : MyServiceInterface {
  return {
    age: null,
    doSomething: function () {
      this.age.someProperty = false;
    }
  };
}

这不会给您编译时错误的原因是因为 thisdoSomething 中的 any 类型。 TypeScript 目前并没有在所有场景中假定 this 的类型,并且无法在函数中指定 this 的类型;但是,有一个开放的 feature request 可以做到这一点。

我建议您更改代码以使用 class:

class MyService implements MyServiceInterface {
    age: number;

    doSomething() {
        this.age.someProperty = false; // error
    }
}

这段代码可读性更强,表达意图更好。

或者,您可以将现有函数更改为:

function myService () : MyServiceInterface {
  return {
    age: null,
    doSomething: function () {
      var self = <MyServiceInterface> this;
      self.age.someProperty = false; // error
    }
  };
}

...这很烦人并且更容易导致开发人员出错。