Explore this example of faltering:
function DecorateClass<T>(instantiate: (...params:any[]) => T){
return (classTarget:T) => { /*...*/ }
}
@DecorateClass((json:any) => {
//This is just an example, the key is to ensure it returns
//an instance specific to the class being decorated.
var instance = new Animal();
instance.Name = json.name;
instance.Sound = json.sound;
return instance;
})
class Animal {
public Name:string;
public Sound:string;
}
I aim to enforce that the anonymous function within the decorator always produces an instance of the relevant class. However, the existing code fails because T actually refers to typeof Animal
and not just Animal
.
In a generic function, is there any way to derive type Animal
from typeof Animal
without needing overly detailed definitions like
function DecorateClass<TTypeOfClass, TClass>
?
It's unfortunate that utilizing typeof in the generic syntax isn't allowed, which was my initial approach to align with what I intend:
function DecorateClass<T>(instantiate: (json:any) => T){
return (classTarget:typeof T) => { /*...*/ } // Cannot resolve symbol T
}