【问题标题】:Symbol.hasInstance returns false on custom objectSymbol.hasInstance 在自定义对象上返回 false
【发布时间】:2019-04-05 04:10:42
【问题描述】:

TypeScript Playground 在 Symbol.hasInstance 内置符号上失败,但对其他人有效。

尝试了其他符号方法Symbol.matchSymbol.replace 工作正常,Symbol.hasInstance 被正确识别,如 console.log 中所示

在 typescript playground 和 MDN 上都试过,生成的代码都返回 false。

TypeScript 代码与 Playground 中一样,您可以将以下内容粘贴到 https://www.typescriptlang.org/play/index.html

class Array1 {
    static [Symbol.hasInstance](instance) {
    console.log(instance);
    return Array.isArray(instance);
  }
}
console.log(Symbol.hasInstance.toString());
let arr: string[] = ['a', 'b'];
console.log(arr instanceof Array1);
console.log([] instanceof Array1);
// expected output: true
// output is false

单击运行时生成的代码无法在左侧返回 true

var Array1 = /** @class */ (function () {
     function Array1() {
    }
    Array1[Symbol.hasInstance] = function (instance) {
        console.log(instance);
        return Array.isArray(instance);
    };
    return Array1;
}());
console.log(Symbol.hasInstance.toString());
var arr = ['a', 'b'];
console.log(arr instanceof Array1);
console.log([] instanceof Array1);

应该返回真而不是假

【问题讨论】:

    标签: arrays typescript symbols


    【解决方案1】:

    官方游乐场不允许您更改太多编译器选项。特别是,它似乎针对 ES5,但 Symbol.hasInstance 仅在 ES2015 及更高版本中可用。如果您使用它作为目标,它会生成有效的代码。试试看here

    但是,即使针对 ES5,如何让它生成工作代码呢?我不确定你为什么需要这样做,因为 Symbol.hasInstance 根本无法在不支持它的引擎中工作,但这里的 TypeScript 也将在官方操场上生成有效的 JavaScript:

    class Array1 { }
    Object.defineProperty(Array1, Symbol.hasInstance, {
        get: () => (instance) => {
            console.log(instance);
            return Array.isArray(instance);
        }
    });
    console.log(Symbol.hasInstance.toString());
    let arr: string[] = ['a', 'b'];
    console.log(arr instanceof Array1);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-18
      • 2012-10-10
      • 2016-02-17
      • 1970-01-01
      • 2012-01-07
      • 2020-04-28
      • 1970-01-01
      • 2021-04-05
      相关资源
      最近更新 更多