For instance, I have the following function:
function createInstanceOf(ObjectConstructor) {
return new ObjectConstructor;
}
I want to make WebStorm autocompletion working when I pass a class as an argument. For example: if I call createInstanceOf(ClassA)
I want to see autocompletion for ClassA
instance, if I call createInstanceOf(ClassB)
– for ClassB
instance. So JSDoc function has to be generic.
It's easy to define a generic function with JSDoc and make @return
value type be the same as @param
, but I've found no way to treat @param
type as a constructor for returned object.
So this doesn't work:
/**
* @param {T} ObjectConstructor
* @returns {T}
* @template T
*/
function createInstanceOf(ObjectConstructor) {
return new ObjectConstructor;
}
I also tried to make it working this way:
/**
* @param {function(new:T)} ObjectConstructor
* @returns {T}
* @template T
*/
function createInstanceOf(ObjectConstructor) {
return new ObjectConstructor;
}
But maybe I use closure types wrong, or WebStorm can't resolve such generic types.
If there're several solutions for JSDoc, I'd like to find out which ones work specifically with WebStorm IDE autocompletion.
Thank you
You probably don't need this anymore, but I too have been stuck on this for months so for other people wondering, you can do it like this:
/**
* @template T
* @param {new() => T} ObjectConstructor
* @returns {T}
*/
function createInstanceOf(ObjectConstructor) {
return new ObjectConstructor;
}
Got the answer from this article
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