[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 bigInt
doesn't include in string | number | boolean