Does not work below codes :
function deco<T>(){
return function(target, key){
// before
// target[key] = new Decorated<T>();
// edited
Object.defineProperty(target, key, {
get(){
return new Decorated<T>();
}
});
}
}
class Decorated<T> {
set(values: T){
}
}
class MyDecos {
@deco<{a: number}>() a;
@deco<{b: string}>() b;
}
const test = new MyDecos;
test.a.set(); // want to throw error
test.a.set({a: '1'); // want to throw error
test.b.set({b: 1); // want to throw error
have any wrong with generic?
assistant displayed values: any
I want to Test.set
methods working with Generic from decorator
Decorators can't change the structure of the class, this limitation is by design. We can use mixins to achieve mutation of the class as described here.
Without a more complete example however, I am not sure why you don't just instatiate the field directly with an insatnce of Decorated<T>
. The decorator version does not seem to add much in this case:
class MyDecos {
a = new Decorated<{ a: number }>();
b = new Decorated<{ b: string }>();
}
const test = new MyDecos;
test.a.set(); // error
test.a.set({ a: '1'); //error
test.b.set({ b: 1); // error
Note Your current decorator implementation is not ok, you assign Decorated
to the target
, target
is the class not an instance of the class so only one Decorated
object will exist for all instances of the class, my guess this is meant to hold instance state so the implementation will cause problems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With