简体   繁体   English

打字稿:属性不存在

[英]Typescript: Property does not exist

I'm trying to develop a decorator for REST Api Interfaces in Typescript. 我正在尝试在Typescript中为REST Api接口开发一个装饰器。 Here it is the decorator implementation 这是装饰器实现

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;
    }
}

Now, I can use the decorator @RemoteResource and the methods post|retrieve|remove|update are added to the original object prototype correctly. 现在,我可以使用装饰器@RemoteResource ,并将方法post|retrieve|remove|update正确地添加到原始对象原型中。

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

From here, if I execute 从这里开始,如果我执行

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

I've the log printed out correctly, but I've also have the following error: "Property 'post' does not exist on type 'Foo'." 我已正确打印日志,但我也有以下错误:“Foo”类型中不存在“属性'帖子'。” While I understand why I'm having this error (Foo doesn't have any declared post property) I'm not sure about how to fix it. 虽然我明白为什么我有这个错误(Foo没有任何声明的post属性)我不知道如何解决它。

Ideally, I would like that the TS compiler understand that the decorator extends the original object adding up those methods. 理想情况下,我希望TS编译器能够理解装饰器扩展了原始对象,从而增加了这些方法。

How can I achieve it? 我怎样才能实现它? Any ideas? 有任何想法吗?

Thanks! 谢谢!

Since you are adding these methods dynamically at runtime in the decorator, the compiler has no way of knowing that these methods will exist for Foo instances. 由于您是在运行时在装饰器中动态添加这些方法,因此编译器无法知道这些方法对于Foo实例是否存在。

You can change that in different ways, for example: 您可以通过不同方式更改它,例如:

(1) Using an interface and intersection: (1)使用接口和交叉点:

interface RemoteResource {
    post(): void;
    remove(): void;
    update(): void;
    retrieve(): void;
}

let tester = new Foo() as Foo & RemoteResource;
tester.post(); // no error

(2) Interface and empty methods: (2)接口和空方法:

export class Foo implements RemoteResource {
    post: () => void;
    remove: () => void;
    update: () => void;
    retrieve: () => void;
}

let tester = new Foo() as Foo & RemoteResource;
tester.post();

Edit 编辑

@Robba suggests: @Robba建议:

(3) Ignore all type checking (3)忽略所有类型检查

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

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM