Typescript 财产';setPrototypeOf';不存在于类型';ObjectConstructor';

Typescript 财产';setPrototypeOf';不存在于类型';ObjectConstructor';,typescript,polyfills,typescript3.0,Typescript,Polyfills,Typescript3.0,我想实现polyfill Object.setPrototypeOf,如下所述: 这是我的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; } d.d.ts: declar

我想实现polyfill Object.setPrototypeOf,如下所述:

这是我的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; 
}
d.d.ts:

declare interface ObjectConstructor{

        setPrototypeOf(obj: any, proto: any);

}
我尝试了polyfill.d.ts的多种可能性:

declare global {

    export interface ObjectConstructor {
        setPrototypeOf(obj: any, proto: any);
    }
}
我仍然有以下错误:

[ts]类型上不存在属性“setPrototypeOf” “对象构造函数”。你是说“getPrototypeOf”吗?lib.es5.d.ts(164, 5) :“getPrototypeOf”在此处声明

我将相当大的应用程序迁移到TypeScript 3.0.3,这就是我需要实现polyfill的原因

找到解决方案:

删除polyfill就足够了,并且:

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)
    }
}
导出类known错误扩展错误{
public isknown错误:布尔值=true;
构造函数(消息:string){
超级(信息);
this.message=消息;
//足够好的溶液,输送至ES5

在tsconfig.json中添加以下内容:

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

我如何处理这个(不理想的)解决方案:

导出类known错误扩展错误{
public isknown错误:布尔值=true;
构造函数(消息:string){
超级(信息);
this.message=消息;
//足够好的溶液,输送至ES5
(Object).setPrototypeOf(this,KnownError.prototype)
}

}
您尝试的
polyfills.d.ts
第一件事应该是有效的。您的
tsconfig.json
文件中是否包含
polyfills.d.ts
?如果您跳转到
ObjectConstructor
上的定义,是否会出现一个菜单,指示您的声明正在与标准库中的声明合并?@MattMcCutchen I我认为你的问题很关键。不。我没有看到Object.setPrototypeOf。在polyfills.ts中,我看到以下错误“[ts]属性'setPrototypeOf'在类型'ObjectConstructor'上不存在。你的意思是'getPrototypeOf'?lib.es5.d.ts(164,5):'getPrototypeOf'在这里声明。”。似乎polyfill.ts不起作用。为了解决我的问题,我阅读了以下内容:如果您在
polyfills.d.ts
中编写
declare var foo:any;
,然后从
polyfill.ts
中引用
foo
,引用是否解析为声明?可能
polyfills.d.ts
不包含在您的项目中。谢谢您的发布找到的解决方案。只是最好把它放在自己的答案中,因为人们通常只阅读问题的开头,然后去寻找答案。老实说,我认为解决方案是对TS的人发牢骚。polyfills解决方案是一个拐杖-