在TypeScript中,为什么访问(get)属性只有一个setter才是错误?

tal*_*xes 11 typescript

为什么编译?(TS v2.0.3)

class SetterOnly {
  set prop(v) {
    let x = this.prop;
  }
}
Run Code Online (Sandbox Code Playgroud)

我希望this.prop生成一个编译时错误...

Sha*_*tin 7

这是一个已知问题:https://github.com/Microsoft/TypeScript/issues/814

我们绝对不会为只写属性而烦恼.这并不足以证明使用类型系统复杂化是合理的.


bas*_*rat 6

TypeScript目前没有概念writeonly.仅仅因为对它的需求不多.但它有readonly:

class ReadOnly {
  get prop() {return 123}
}

const readonly = new ReadOnly();
readonly.prop = 123; // Error 
Run Code Online (Sandbox Code Playgroud)