Property 'setPrototypeOf' does not exist on type 'ObjectConstructor'

2.2k Views Asked by At

I want to implement polyfill Object.setPrototypeOf as is descrbed in:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf

It is my polyfill.ts:

// Only works in Chrome and FireFox, does not work in IE:
Object.setPrototypeOf = Object.setPrototypeOf || function(obj, proto) {
    obj.__proto__ = proto;
    return obj; 
}

polyfills.d.ts:

declare interface ObjectConstructor{

        setPrototypeOf(obj: any, proto: any);

}

I was trying with many possibilities of polyfill.d.ts:

declare global {

    export interface ObjectConstructor {
        setPrototypeOf(obj: any, proto: any);
    }
}

and still I have following error:

[ts] Property 'setPrototypeOf' does not exist on type 'ObjectConstructor'. Did you mean 'getPrototypeOf'? lib.es5.d.ts(164, 5): 'getPrototypeOf' is declared here.

I migrate quite large application to TypeScript 3.0.3 that is why I need to implement the polyfill.

Found solution:

It is good enough to delete polyfill and:

export class KnownError extends Error {
    public isKnownError: boolean = true;

    constructor(message: string) {
        super(message);
        this.message = message;
        //good enough solution, transpiled to ES5
        (<any>Object).setPrototypeOf(this, KnownError.prototype)
    }
}

More: Typescript - Extending Error class

2

There are 2 best solutions below

0
On BEST ANSWER

The way how I coped with that (not ideal) solution:

export class KnownError extends Error {
    public isKnownError: boolean = true;

    constructor(message: string) {
        super(message);
        this.message = message;
        //good enough solution, transpiled to ES5
        (<any>Object).setPrototypeOf(this, KnownError.prototype)
    }
}
0
On

Add to the tsconfig.json this:

{
  "compilerOptions": {
    "lib": [
      ...
      "es7"
    ]
  }
}