Getters and setters with unrelated types
Accept text on assignment, validate it in the setter, and give readers a number with an independently typed getter.
You read a retry limit from a text field, but the code that schedules retries needs a number. If you give the property a union, its readers have to narrow the type even after you parse the input. Give the read and write sides their own types.
Parse at the setter
A class can accept a string in an assignment and return a number when you read that same property. Write the parameter and return annotations on the two accessors. TypeScript 5.1 introduced unrelated accessor types when both sides have explicit annotations.
class RetrySettings {
#limit = 0
get limit(): number {
return this.#limit
}
set limit(input: string) {
const limit = Number(input)
if (!/^\d+$/.test(input) || !Number.isSafeInteger(limit)) {
throw new RangeError('Use a non-negative integer')
}
this.#limit = limit
}
}
const settings = new RetrySettings()
settings.limit = '3'
console.log(settings.limit + 1)Run the file with a TypeScript-aware runner and you get 4. The getter supplies a number to the addition. The setter handles the conversion and leaves the previous value in place if validation throws.
The setter accepts decimal digits within the safe-integer range. Try assigning 'three' after '3': the setter throws a RangeError and the getter still returns 3.
Check assignments with the write type
The different types become visible when you assign the property to itself. Append this line to the example and run your TypeScript checker.
settings.limit = settings.limitThe checker reports Type 'number' is not assignable to type 'string'. Each occurrence gets its type from its role in the expression. The right side reads a number from the getter, and the left side expects the string parameter of the setter.
Before 5.1, the checker required the getter's type to be assignable to the setter's type. That kept a self-assignment legal. With both types explicit, the setter can require a string even when the getter returns a number.
If you need to assign the current value back to the property, convert it with String(settings.limit). If your callers often start with numbers, consider accepting numbers in the setter too.