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

痴心易碎 提交于 2019-12-10 18:20:23

问题


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


回答1:


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)
    }
}



回答2:


Add to the tsconfig.json this:

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


来源:https://stackoverflow.com/questions/52402166/property-setprototypeof-does-not-exist-on-type-objectconstructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!