我创建一个类型别名,如下所示
export type Nullable<T> = T | null | undefined;
我希望有一个扩展方法hasValue
来检查实例是否为空或未定义。我尝试使用prototype作为
Nullable.prototype.hasValue = function(): boolean => {
return Nullable<T>(this) === null || Nullable<T>(this) === undefined
}
然而,我得到了以下错误。
“‘Nullable”仅指类型,但此处用作值。
有人能帮帮忙吗?谢谢。
发布于 2021-01-14 22:02:07
以下是我的评论中的建议作为答案:
您看到的编译器错误试图指出type
定义不会生成任何代码,仅用于类型检查。
要定义可在Nullable
实例上调用的hasValue
方法,必须将Nullable
定义为class
。使用此选项需要注意的是,它将产生一些开销(例如,必须创建包封值的实例)。
一个基本的例子:
class Nullable<T> {
value: T;
constructor(value: T) {
this.value = value;
}
hasValue() {
return this.value != null;
}
/* ... */
}
或者,您可以将hasValue
定义为接受Nullable
参数的自由函数。
https://stackoverflow.com/questions/65693008
复制相似问题