microsoft / microsoft/TypeScript
Allow setters to return
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
Search Terms
Setters cannot return a value
decorators
Suggestion
By default JavaScript does nothing with the return value of a setter, but it isn't an error.
Allow setters to return as the default behaviour and add flag to turn errors on.
Use Cases
- Decorators that override the setter and use the original setters return value.
- Methods that directly call the setter function and expect a return.
Examples
A live example would be @computed from ember-decorators, which matches the old behaviour from ember.
Code example using legacy decorators (same would be possible with stage 2 decorators):
function saved (target: {}, key: string | symbol, descriptor: PropertyDescriptor) {
const savedStore = new WeakMap();
const oldSet = descriptor.set;
if (!oldSet) {
throw new Error('Must be used on setter only');
}
const oldGet = descriptor.get;
return {
...descriptor,
get () {
let response = savedStore.get(this);
if (!response && oldGet) {
response = oldGet.call(this);
}
return response;
},
set (value: any) {
const result = oldSet.call(this, value);
savedStore.set(this, result);
}
};
}
class Foo {
@saved
get square () {
// default value of 1 if none is saved
return 1;
}
set square (value: number) {
return value * value;
}
}
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript / JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. new expression-level syntax)
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reviewing the setter and decorator behavior described in the issue, including the legacy decorator example and its use of PropertyDescriptor.set. Compare the requested default return behavior with the proposed opt-in error flag and existing JavaScript behavior. Done means the language behavior and flag semantics are specified and covered by appropriate compiler tests.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100