使用属性装饰器严格检查属性类型 [英] Strict type checking for property type with property decorator
本文介绍了使用属性装饰器严格检查属性类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法可以验证Typescript中装饰的属性的类型?我想要一个仅适用于 boolean
类属性的属性装饰器,而不适用于例如字符串
(下面的示例)。
Is there a way to validate the type of the property that is decorated in Typescript? I would like a property decorator that only works on boolean
class properties, but not on e.g. string
(example below). Is this possible?
(注意:我不希望通过reflect-metadata进行运行时验证,而只是使用Typescript进行编译类型警告。)
function booleanProperty<T extends HTMLElement>(target: T, prop: string) {
// `target` will be the class' prototype
Reflect.defineProperty(target, prop, {
get(this: T): boolean {
return this.hasAttribute(prop);
},
set(this: T, value: boolean): void {
if (value) {
this.setAttribute(prop, '');
} else {
this.removeAttribute(prop);
}
}
});
}
class MyElement extends HTMLElement {
@booleanProperty
foo: boolean;
@booleanProperty
bar: string; // TS compile error
}
customElements.define('my-element', MyElement);
推荐答案
这怎么办?
function booleanProperty<
T extends HTMLElement & Record<K, boolean>,
K extends string>(target: T, prop: K) {
// ... impl here
}
传入的目标
必须是 HTMLElement
在键 K
中具有 boolean
属性,其中 K
是传入的 prop
的类型。让我们看看它是否有效:
The passed-in target
needs to be an HTMLElement
which has a boolean
property at the key K
, where K
is the type of the passed-in prop
. Let's see if it works:
class MyElement extends HTMLElement {
@booleanProperty // okay
foo: boolean;
@booleanProperty // error
bar: string;
}
对我来说很好。这样对您有用吗?
Looks good to me. Does that work for you?
这篇关于使用属性装饰器严格检查属性类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文