打字稿类型检查无法与我的装饰器

时间:2017-11-22 14:05:20

标签: javascript typescript decorator

在我的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方法我需要强制xyXY类型,因为TS会抱怨xy可以是XY或者XYLiteral否则。但是,我的装饰者将始终确保xy的类型为XY

TS是否有可能知道xy只能是XY类型,同时允许XYXYLiteral类型作为参数传递(没有像我上面那样强迫类型?)

1 个答案:

答案 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