强制规范通用闭包类型 [英] Forcing specification of a generic Closure type

查看:69
本文介绍了强制规范通用闭包类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,如果未能在Closure中指定泛型类型参数,则不会引发错误.这与许多其他语言(包括TypeScript)不同.闭包会将类型视为未知"类型,通常将其忽略. (可以设置编译器标志以使其抱怨未知类型,但是只能在全局范围内设置它们,并且通常太吵而不能真正使用.)

Generally, if you fail to specify a generic type parameter in Closure, it won't raise an error. This is different than many other languages, including TypeScript. Closure will treat the type as an "unknown" type, which are usually ignored. (It's possible to set compiler flags to have it complain about unknown types, but these can only be set globally and often too noisy to really use.)

我有一个Closure类,Response<T>.我希望所有Response实例都为<T>指定一种类型,而不只是简单地保留它的类型.为此,每当您尝试实例化通用实例时,我都想强制执行编译时错误,以便我可以查找并修复所有此类实例.

I have a Closure class, Response<T>. I would like all Response instances to specify a type for <T>, not simply leave it untyped. To do that, I'd like to force a compile-time error whenever you try to instantiate a generic instance, so I can find and fix all such instances.

我一直试图从

I've been trying to coerce this behaviour out of the Closure Type Transformation Language, but nothing I try is actually creating an error. Here's my latest attempt, but it seems to be ignored:

/**
 * @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;
  }
}

作为一种对策,我一直在将任何未知/未指定的泛型类型转换为undefined类型,因为这将鼓励编译器针对潜在的不安全使用方式引发更多错误:

As a half-measure, I've been converting any unknown/unspecified generic types to the undefined type, because that will encourage the compiler to raise more errors for potentially-unsafe use:

 * @template OPT_RESPONSE_TYPE
 * @template RESPONSE_TYPE := cond(isUnknown(OPT_RESPONSE_TYPE), 'undefined', OPT_RESPONSE_TYPE) =:

在Closure中是否还有其他更直接的方法要求规范泛型类型参数?

Is there any more direct way to require specification of a generic type parameter in Closure?

推荐答案

这可能是您可以使用

This is probably something you could do with a custom conformance config. If you are brave enough to delve into the undocumented type transformation language, that shouldn't be a problem either.

这篇关于强制规范通用闭包类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆