Reputation: 129785
I am working on reducing the use of accidentally-unknown generic type parameters in a code base. I am using a Closure TTL incantation like the following to coerce unknown generic types to the undefined
type, hopefully provoking errors that let me find these cases (see this related question).
* @template T
* @template TYPE_I_ACTUALLY_USE := cond(isUnknown(T), 'undefined', T) =:
That has brought me to a case like this:
/**
* @template T
* @template R := cond(isUnknown(T), 'undefined', T) =:
* @param {function():R} factory
* @return {{prop: R}}
*/
function factoryWrapper(factory) {
return {prop: factory()};
}
var instance = factoryWrapper(() => 2);
This factoryWrapper
function takes a factory
function that produces a value of type R
, calls it, and wraps the result in {prop: ...}
, for a return type of {prop: R}
. But because I don't specify T
or R
when calling factoryWrapper
, it doesn't know what type they're supposed to be, and can't tell whether the provided factory function returns the right type, so it produces an error or untyped output:
input0:11: WARNING - inconsistent return type
found : number
required: undefined
var instance = factoryWrapper(() => 2);
In a language with a native type annotation syntax, like TypeScript, I might fix this by including the generic type parameter in the invocation:
var instance = factoryWrapper<number>(() => 2);
However, I haven't been able to figure out any equivalent syntax for Closure. I took a few guesses, like the following, but none worked.
var instance = factoryWrapper/** <number> */(() => 2);
How do I specify generic type parameters for a function invocation in Closure JavaScript?
Upvotes: 2
Views: 536
Reputation: 581
Closure Compiler doesn't allow you to specify type parameters when calling a generic function. But I think casting the callback will do what you want. Something like:
var instance = factoryWrapper(/** @type {function(): number} */ (() => 2));
Upvotes: 3