Failure to specify a generic type parameter in Closure generally does not result in an error, unlike languages such as TypeScript. In Closure, the unspecified type is treated as "unknown", often being ignored. (Although it is possible to adjust compiler flags to report unknown types, this can be too disruptive when set globally.)
In my Closure class Response<T>
, I want every instance of Response
to declare a type for <T>
, rather than leaving it untyped. To enforce this, I aim to trigger a compile-time error whenever a generic instance is instantiated, allowing me to identify and rectify such instances.
I have been attempting to induce this behavior using the Closure Type Transformation Language, but so far my efforts have not resulted in an error. My latest endeavor is outlined below:
/**
* @template OPT_RESPONSE_TYPE
* @template RESPONSE_TYPE := cond(
* !isUnknown(OPT_RESPONSE_TYPE),
* OPT_RESPONSE_TYPE,
* printType(
* 'ERROR: Please specify a non-generic type for Response',
* typeExpr('ERROR')
* )
* ) =:
*
* @param {RESPONSE_TYPE=} value
*/
const Response = class {
constructor(value = undefined) {
/** @const */
this.value = value;
}
}
To prompt more errors for potentially risky usage, I have resorted to converting any unknown or unspecified generic types to the undefined
type:
* @template OPT_RESPONSE_TYPE
* @template RESPONSE_TYPE := cond(isUnknown(OPT_RESPONSE_TYPE), 'undefined', OPT_RESPONSE_TYPE) =:
Is there a more straightforward method to mandate the specification of a generic type parameter in Closure?