首页 文章

打字稿:属性不存在

提问于
浏览
2

我正在尝试在Typescript中为REST Api接口开发一个装饰器 . 这是装饰器实现

export function RemoteResource(params: any): Function {
    console.log("RemoteResource.params: ", params);
    return function (target: Function) {

        //--POST
        target.prototype.post = function () {
            console.log("----POST");
        };

        //--GET
        target.prototype.retrieve = function () {
            console.log("----GET");
        };

        //--DELETE
        target.prototype.remove = function () {
            console.log("----DELETE");
        };

        //--PULL
        target.prototype.update = function () {
            console.log("----PULL");
        };

        console.log("RemoteResource.target: ", target);

        return target;
    }
}

现在,我可以使用装饰器 @RemoteResource 并将方法 post|retrieve|remove|update 正确添加到原始对象原型中 .

@RemoteResource({
    path: "/foos",
    methods: [],
    requireAuth: false
})
export class Foo { }

从这里开始,如果我执行

let tester = new Foo();
tester.post() //--This prints out "----POST" correctly

我've the log printed out correctly, but I'也有以下错误:"Property 'post' does not exist on type 'Foo'."虽然我明白为什么我'm having this error (Foo doesn' t有任何声明 post 属性)我不知道如何解决它 .

理想情况下,我希望TS编译器能够理解装饰器扩展了原始对象,从而增加了这些方法 .

我怎样才能实现它?有任何想法吗?

谢谢!

1 回答

  • 2

    由于您是在运行时在装饰器中动态添加这些方法,因此编译器无法知道 Foo 实例将存在这些方法 .

    您可以通过不同方式更改它,例如:

    (1)使用接口和交叉点:

    interface RemoteResource {
        post(): void;
        remove(): void;
        update(): void;
        retrieve(): void;
    }
    
    let tester = new Foo() as Foo & RemoteResource;
    tester.post(); // no error
    

    (2)接口和空方法:

    export class Foo implements RemoteResource {
        post: () => void;
        remove: () => void;
        update: () => void;
        retrieve: () => void;
    }
    
    let tester = new Foo() as Foo & RemoteResource;
    tester.post();
    

    编辑

    @Robba建议:

    (3)忽略所有类型检查

    let tester = new Foo() as any;
    tester.post();
    

    要么

    let tester = new Foo();
    tester["post"]();
    

相关问题