【问题标题】:Typescript type checking not working with my decorator打字稿类型检查不适用于我的装饰器
【发布时间】: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 方法中我需要强制xyXY 类型,因为TS 会抱怨xy 可以是XYXYLiteral,否则。但是,我的装饰器将始终确保 xy 的类型为 XY

TS 是否有可能知道 xy 只能是 XY 类型,同时允许 XYXYLiteral 类型作为参数传递(而不像我正在做的那样强制类型以上)?

【问题讨论】:

    标签: javascript typescript decorator


    【解决方案1】:

    您可以添加一个包含联合类型参数的重载,并让实现具有实际参数类型:

    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

    【讨论】:

    • 不确定你是否可以像这样重载,因为解释器不知道在给定 XY 参数的情况下选择哪种方法。
    • 经过测试的作品,出现的唯一重载是 VS 代码智能感知是联合类型的重载。这是反直觉的:)
    • 哦,好吧,我没有看到你实际上只实现了 XY 类型。
    猜你喜欢
    • 2019-10-13
    • 2018-12-16
    • 2020-01-17
    • 2016-12-05
    • 2018-11-03
    • 2020-01-02
    • 2023-03-23
    • 2017-04-02
    • 2019-03-25
    相关资源
    最近更新 更多