[Typescript] Different types for Getter / Setter in a class

You can give Getter or Setter different types. So that Setter can accpet a wider range of types, while Getter can return a narrow type.

class Thing {
  #size = 0
  get size(): number {
    return this.#size
  }
  set size(value: string | number | boolean) {
    let num = +value;
    this.#size = Number.isFinite(num) ? num : 0
  }
}

let thing = new Thing()

thing.size = 33
thing.size = "123.123"
thing.size = false

 

Notice that you cannot change Getter to bigInt, because bigIntdoesn't include in string | number | boolean

posted @ 2022-11-18 15:22  Zhentiw  阅读(31)  评论(0编辑  收藏  举报