在我的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
类型作为参数传递(没有像我上面那样强迫类型?)
答案 0 :(得分:2)
您可以添加包含union类型参数的重载,并使实现具有实际参数类型:
setCenter(xy: XY | XYLiteral): void;
@XYLiteralDecorator
setCenter(xy: XY ): void {
console.log(xy.getX());
}
这可以按预期工作,您可以使用任一类型调用,实现将知道实际类型:
dds.setCenter(new XY(0,0));
dds.setCenter([1, 1]);
完整样本here