typescriptdefineproperty

this keyword when extending external js objects properties in ts


I'm converting a codebase from js to ts and stumbled upon a conundrum: extending external js object property getters and setters.

interface Player {
    name: string;
    position: { x: number; y: number };
    _posHistory: [{ x: number; y: number }];
    structures: Structures[];
}
Object.defineProperty(Player.prototype, "position", {
    get() {
        return this.pos;   // i get "Unsafe member access .pos on an any value"
    },
    set(pos) {
        this._posHistory.push(pos);  //same here
        this.pos = pos;              //and here
    },
    configurable: false
});

How do I go about type hinting "this" keyword to TS in this situation so its not "any"?


Solution

  • First than all you are trying to use Player as a value, but it is defined as a type. You can convert your interface for a class to being able to use it on the defineProperty method.

    Second it seams to me that sadly the Object.defineProperty method lacks of type definitions. But I will leve you a link to a post to create a complete typed method to work with.

    https://fettblog.eu/typescript-assertion-signatures/