【发布时间】:2017-11-22 14:05:20
【问题描述】:
在我的Map 类中考虑以下方法:
@XYLiteralDecorator
setCenter(xy: XY | XYLiteral): void {
this.mapI.centerAt((<XY>xy).projectToPoint(3978));
}
这是上面使用的@XYLiteralDecorator 装饰器:
function XYLiteralDecorator(target: Object, propertyKey: string, descriptor: TypedPropertyDescriptor<any>) {
const originalMethod = descriptor.value;
descriptor.value = function(maybeXY: XY | XYLiteral): XY {
return originalMethod.apply(this, [isXYLiteral(maybeXY) ? new XY(maybeXY[0], maybeXY[1]) : maybeXY]);
};
return descriptor;
}
您会注意到在setCenter 方法中我需要强制xy 为XY 类型,因为TS 会抱怨xy 可以是XY 或XYLiteral,否则。但是,我的装饰器将始终确保 xy 的类型为 XY。
TS 是否有可能知道 xy 只能是 XY 类型,同时允许 XY 或 XYLiteral 类型作为参数传递(而不像我正在做的那样强制类型以上)?
【问题讨论】:
标签: javascript typescript decorator