简体   繁体   English

错误类型错误:构造函数 Map 在 ES5 中需要“新”?

[英]ERROR TypeError: Constructor Map requires 'new' in ES5?

Code is:代码是:

export class ExtendedMap<T, U> extends Map {
    constructor() {
        super();
    }

    toggle(key: T, value: U) {
        if (this.has(key)) {
            super.delete(key);
        } else {
            super.set(key, value);
        }
    }

    has(key: T): boolean {
        return super.has(key);
    }
}

I get this error for ES5 compilation: ES5 编译时出现此错误:

ERROR TypeError: Constructor Map requires 'new'错误类型错误:构造函数 Map 需要“新”

I'm using it like this:我这样使用它:

public registryLayers = new ExtendedMap<number, any>();

Snippet (without TypeScript parts commented out):片段(没有 TypeScript 部分注释掉):

 /*export*/ class ExtendedMap/*<T, U>*/ extends Map { constructor() { super(); } toggle(key/*: T*/, value/*: U*/) { if (this.has(key)) { super.delete(key); } else { super.set(key, value); } } has(key/*: T*/)/*: boolean*/ { return super.has(key); } } /*public*/ registryLayers = new ExtendedMap/*<number, any>*/(); console.log("Worked without error");

TypeScript should be complaining about Map if you're targeting ES5 (it does in this example ).如果你的目标是 ES5,TypeScript 应该抱怨Map在这个例子中就是这样)。

If you ignore that error from TypeScript and then run the code that TypeScript generates in a modern(ish) JavaScript engine, the problem is that the code TypeScript created is trying to call Map like an old-style constructor function. If you ignore that error from TypeScript and then run the code that TypeScript generates in a modern(ish) JavaScript engine, the problem is that the code TypeScript created is trying to call Map like an old-style constructor function. When you configure TypeScript to emit ES5 code, it doesn't emit class constructs because ES5 didn't have them.当您将 TypeScript 配置为发出 ES5 代码时,它不会发出class构造,因为 ES5 没有它们。 Instead, it emits constructor function syntax, and in your ExtendedMap constructor, it tries to call Map like this:相反,它发出构造函数 function 语法,并且在您的ExtendedMap构造函数中,它尝试像这样调用Map

return _super.call(this) || this; // Where `_super` is set to `Map`

But in a modern environment, Map is defined as a class constructor and cannot be called that way, resulting in the error you're getting.但是在现代环境中, Map被定义为class构造函数,不能这样调用,从而导致您遇到错误。

If you need your code to run in an ES5 environment, you need to include a Map polyfill (since Map didn't exist in ES5) that is written to be compatible with an ES5 environment so that Map can be called via .call as above.如果你需要你的代码在 ES5 环境中运行,你需要包含一个Map .call因为Map在 ES5 中不存在),它被编写为与 ES5 环境兼容,这样Map就可以被称为上述 6 的调用。 . And if your code is running in a modern(ish) environment that already has Map , you'll still need to include the polyfill because of the way it gets called.如果您的代码在已经具有Map的现代(ish)环境中运行,您仍然需要包含 polyfill,因为它被调用的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM