Joh*_*isz 5 decorator typescript
我在TypeScript中有一个属性装饰器,只能在类型的属性上使用Array.要强制执行此操作,TypeError如果属性类型不是,则在运行时抛出a Array(使用反射元数据获取属性类型信息):
function ArrayLog(target: any, propertyKey: string) {
if (Reflect.getMetadata("design:type", target, propertyKey) !== Array) {
throw new TypeError();
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
但是,我不会认为这太开心了.我怎么能这样做,以便TypeScript编译器只允许在某种类型的属性上使用某个属性装饰器?
您收到的错误是由于缺少返回表达式造成的。
尝试一些类似的事情:
export function Decorator(fn:any) {
return (target: Object, propertyKey: string, descriptor: TypedPropertyDescriptor<Array>) => {
if (Reflect.getMetadata("design:type", target, propertyKey) !== Array) {
throw new TypeError();
}
return descriptor;
};
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
820 次 |
| 最近记录: |