Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 641
Tomasz Waszczyk Avatar asked Jun 27 '26 01:06

Tomasz Waszczyk


2 Answers

Add to the tsconfig.json this:

{
  "compilerOptions": {
    "lib": [
      ...
      "es7"
    ]
  }
}
like image 137
Nurbol Alpysbayev Avatar answered Jul 01 '26 03:07

Nurbol Alpysbayev


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)
    }
}
like image 22
Tomasz Waszczyk Avatar answered Jul 01 '26 03:07

Tomasz Waszczyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!