繁体   English   中英

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

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

代码是:

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

ES5 编译时出现此错误:

错误类型错误:构造函数 Map 需要“新”

我这样使用它:

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

片段(没有 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");

如果你的目标是 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. 当您将 TypeScript 配置为发出 ES5 代码时,它不会发出class构造,因为 ES5 没有它们。 相反,它发出构造函数 function 语法,并且在您的ExtendedMap构造函数中,它尝试像这样调用Map

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

但是在现代环境中, Map被定义为class构造函数,不能这样调用,从而导致您遇到错误。

如果你需要你的代码在 ES5 环境中运行,你需要包含一个Map .call因为Map在 ES5 中不存在),它被编写为与 ES5 环境兼容,这样Map就可以被称为上述 6 的调用。 . 如果您的代码在已经具有Map的现代(ish)环境中运行,您仍然需要包含 polyfill,因为它被调用的方式。

暂无
暂无

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

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