Setters Accept Wider Types Than Getters
Give one property a narrow read type and a wider write type: the setter accepts string or number while the getter always hands back a number.
Code
interface Temperature {
get celsius(): number;
set celsius(value: number | string);
}
class Sensor implements Temperature {
private stored = 0;
get celsius(): number {
return this.stored;
}
// setter 收宽类型:字符串会先转数字再存,getter 恒返回 number
set celsius(value: number | string) {
this.stored = typeof value === 'string' ? Number.parseFloat(value) : value;
}
}
const sensor = new Sensor();
sensor.celsius = 21.5;
console.log('numeric set:', sensor.celsius);
sensor.celsius = '18.5';
console.log('string set:', sensor.celsius);
// 经接口使用同样成立:写侧宽、读侧窄
const probe: Temperature = sensor;
probe.celsius = '25';
console.log('via interface:', probe.celsius);
const read: number = sensor.celsius;
console.log('read type is number:', read);Output
Captured from a sandboxed run of this snippet in the build pipeline.
numeric set: 21.5
string set: 18.5
via interface: 25
read type is number: 25How it works
Count the class Sensor as the entire surface area of Setters Accept Wider Types Than Getters.
Module-level bindings hold the data — sensor — with no function scope in between.
Putting it to use
The demo output is labeled (numeric set:, string set:, via interface:), so every printed line ties back to the operation behind it.
Core lines
this.stored = typeof value === 'string' ? Number.parseFloat(value) : value;
set celsius(value: number | string);
const read: number = sensor.celsius;
Interactive Tools for This Topic
Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. Its state lives in module-level bindings: `sensor`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.