javascript - Typescript: Property does not exist -
i'm trying develop decorator rest api interfaces in typescript. here 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, can use decorator @remoteresource
, methods post|retrieve|remove|update
added original object prototype correctly.
@remoteresource({ path: "/foos", methods: [], requireauth: false }) export class foo { }
from here, if execute
let tester = new foo(); tester.post() //--this prints out "----post" correctly
i've log printed out correctly, i've have following error: "property 'post' not exist on type 'foo'." while understand why i'm having error (foo doesn't have declared post
property) i'm not sure how fix it.
ideally, ts compiler understand decorator extends original object adding methods.
how can achieve it? ideas?
thanks!
since adding these methods dynamically @ runtime in decorator, compiler has no way of knowing these methods exist foo
instances.
you can change in different ways, example:
(1) using interface , intersection:
interface remoteresource { post(): void; remove(): void; update(): void; retrieve(): void; } let tester = new foo() foo & remoteresource; tester.post(); // no error
(2) interface , empty methods:
export class foo implements remoteresource { post: () => void; remove: () => void; update: () => void; retrieve: () => void; } let tester = new foo() foo & remoteresource; tester.post();
edit
@robba suggests:
(3) ignore type checking
let tester = new foo() any; tester.post();
or
let tester = new foo(); tester["post"]();
Comments
Post a Comment