使用ES6 Symbols与typescript

4

我试图运行这段简单的代码:

let FUNJECTOR_KEY = Symbol.for('funjector')

但我一直收到错误消息 — 无法找到名称“Symbol”。 我是TypeScript的新手,所以我不确定是否需要包含某些内容?

在我的情况下,我不想使用polyfill,如此处所述—在TypeScript中使用ES6符号


我不想使用polyfill。 - tusharmath
你的编译目标是ES5还是ES6? - jfriend00
我明白了!默认情况下它是编译成 ES5 的,我把目标改成了 ES6,然后它就可以工作了! - tusharmath
1个回答

6

TypeScript编译器将TS转换为JS。在es5模式下,TSC找不到Symbol的声明。因此,您的错误纯粹是编译时错误。您不需要运行时的polyfill。

为了解决这个问题,您可以将编译目标更改为es6,这样Symbol就会在标准库中定义。或者您可以手动添加定义(来源)。

declare class Symbol {
    /** Returns a string representation of an object. */
    toString(): string;

    /** Returns the primitive value of the specified object. */
    valueOf(): Object;

    /**
      * Returns a new unique Symbol value.
      * @param  description Description of the new Symbol object.
      */
    constructor(description?: string);

    /**
    * Returns a Symbol object from the global symbol registry matching the given key if found.
    * Otherwise, returns a new symbol with this key.
    * @param key key to search for.
    */
    static for(key: string): Symbol;

    /**
      * Returns a key from the global symbol registry matching the given Symbol if found. 
      * Otherwise, returns a undefined.
      * @param sym Symbol to find the key for.
      */
    static keyFor(sym: Symbol): string;
}

// Well-known Symbols
declare module Symbol {
    /** 
      * A method that determines if a constructor object recognizes an object as one of the 
      * constructor’s instances.Called by the semantics of the instanceof operator. 
      */
    const hasInstance: Symbol;

    /** 
      * A Boolean value that if true indicates that an object should be flatten to its array 
      * elements by Array.prototype.concat.
      */
    const isConcatSpreadable: Symbol;

    /** 
      * A Boolean value that if true indicates that an object may be used as a regular expression. 
      */
    const isRegExp: Symbol;

    /** 
      * A method that returns the default iterator for an object.Called by the semantics of the 
      * for-of statement. 
      */
    const iterator: Symbol;

    /** 
      * A method that converts an object to a corresponding primitive value.Called by the 
      * ToPrimitive abstract operation. 
      */
    const toPrimitive: Symbol;

    /** 
      * A String value that is used in the creation of the default string description of an object.
      * Called by the built- in method Object.prototype.toString. 
      */
    const toStringTag: Symbol;

    /** 
      * An Object whose own property names are property names that are excluded from the with 
      * environment bindings of the associated objects.
      */
    const unscopables: Symbol;
}

注意: 一些类型检查在符号上不起作用。例如,您不能在接口上声明一个计算为符号的属性。

当前TypeScript中Symbol的限制 https://github.com/Microsoft/TypeScript/issues/5579 - Herrington Darkholme

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接