You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Recognize property with name defined by constant in Object.defineProperty #38115
(Note: I'm using TS in JS files, have basically no knowledge about "pure" TS)
Compiler should recognize prototype property added using Object.defineProperty with name defined not only by string constant but also a string variable, e.g.:
Playground Link
(included also desired behavior for decorators, but as it's experimental feature, you won't propably even consider it)
I understand it's not always possible to make sure variable with property name is not reassigned during runtime, but it seems that TS compiler can handle detection of "static" variables that have known value during compilation.
Use Cases
This way we could define class properties using "single source" and not duplicating code. For example a class providing access to key-value pairs object in a dotted notation instead of string values for keys, whilst the object can be used for another purpose.
Examples
// i can use these somewhere else, e.g. as a type
export const defaults = {
one: 1,
two: 2
}
// properties added in defineProperty
export class Test {
// i don't want to repeat myself
one = defaults.one;
/** @param {keyof defaults} key */
get(key) {
return defaults[key];
}
}
Object.keys(defaults).forEach((key) =>
Object.defineProperty(Test.prototype, key, { get: () => defaults[key] })
);
const inst = new Test();
inst.one; // who would not like this?
inst.get('one'); // instead of this
EDIT: Added a more detailed example with static properties and generics: Playground Link
Is there a way how to make generics work with a single parameter?
JavaScript version: Playground Link (had to remove decorator as it's not working even tho decorator support was enabled)
Activity
sKopheK commentedon Apr 27, 2020
How much ugly is this workaround :)?
Playground Link
EDIT: Added a more detailed example with static properties and generics: Playground Link
Is there a way how to make generics work with a single parameter?
JavaScript version: Playground Link (had to remove decorator as it's not working even tho decorator support was enabled)