0

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"?

DoktorD
  • 15
  • 5
  • Player is an externally defined Object. in a global array which changes as players go offline and online. the interface just defines the Player properties im using + the ones i added. it describes the player object for TS usage. im extending the prototype so every item of that array can behave the same and i dont have to wrap each individual object in a class and keed track of the array updating – DoktorD Apr 28 '21 at 02:08

1 Answers1

0

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/

Iván E. Sánchez
  • 1,183
  • 15
  • 28
  • it is a value but that link seems promising. 2 hrs of googling didnt give me that link. thank you good sir – DoktorD Apr 28 '21 at 02:11
  • 1
    the assert hack works like charm tho is hard to make a generic assertion over T. thankfully i dont need to many – DoktorD Apr 28 '21 at 03:04