Allow Object.defineProperty() to definitely assign properties
See original GitHub issueSuggestion
✅ Viability 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. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript’s Design Goals.
⭐ Suggestion
It would be nice if Object.defineProperty()
and Object.defineProperties()
calls could be read via the constructor to definitely assign class properties.
📃 Motivating Example
class Greeter {
name: string;
greeting: string;
constructor(name: string) {
this.name = name;
Object.defineProperty(this, "greeting", {
get() {
return `hello ${name}`
}
});
}
}
Currently the greeting property in the class will cause the error Property 'greeting' has no initializer and is not definitely assigned in the constructor.
💻 Use Cases
This is not a big deal because we can use a “definite assignment assertion“ (!
) after the greeting property identifier, but it would be nice for TypeScript to be aware of these defineProperty
calls.
🔍 Search Terms
constructor, Object.defineProperty, Object.defineProperties, definitely assigned, strictPropertyInitialization, definite assignment operator Property has no initializer and is not definitely assigned in the constructor.
This is potentially a duplicate of the following issues:
- https://github.com/microsoft/TypeScript/issues/28694 The same issue, but focused on JavaScript source files.
- https://github.com/microsoft/TypeScript/issues/38115 Might be a duplicate of this issue, but the phrasing of this issue is a little less clear to me based on the examples.
Feel free to close as duplicate!
Issue Analytics
- State:
- Created 3 years ago
- Reactions:6
- Comments:6 (2 by maintainers)
Top GitHub Comments
This suggestion only speaks of class properties but it would also be desirable for regular objects.
Consider this callable object with regular assignment:
This correctly produces:
If I want
x
to be not configurable, not enumerable, and not writable then I have to use defineProperty:But the
x
property is now missing on the type. I would expect instead to get:I don’t know if there needs to be a separate issue created for supporting regular objects.
I run into the same problem with this much simpler code:
Now I can use
!
or I can duplicate the logic inside of setData, but it seems a bit naive of the ts compiler to not follow a call to a function onthis
before it decides the code is noncompliant.