如何处理这个盲点?

时间:2017-05-13 15:24:21

标签: typescript

我正在玩打字稿,无法弄清楚为什么打字稿在这种特殊情况下不会进行类型计划。 'this.a.method()'应该出现错误,但一切都很好。我希望打字稿告诉我a.method()需要string值作为参数。我错过了什么?

class A {
  method(value: string){
    console.log(value);
  }
}
class B {
  constructor(private a){}
  call(){
    this.a.method()
  }
}
const a = new A();
const b = new B(a);
b.call();

2 个答案:

答案 0 :(得分:1)

通过在B的构造函数中指定private a;的类型。 它应该是constructor(private a: A){}

class A {
  method(value: string){
    console.log(value);
  }
}
class B {
  constructor(private a: A){}
  call(){
    this.a.method()
  }
}
const a = new A();
const b = new B(a);
b.call();

显然,您需要在this.a.method()处出现编译错误,因为您需要将字符串作为参数传递:this.a.method("foo")

答案 1 :(得分:1)

如果您没有指定变量或属性的类型,则假定其类型为any,而any实际上代表don't do type checking here。它与类型object不同。如果您希望打字稿进行类型检查,请为您的媒体资源a添加constructor(private a: SomeType) { }

类型