簡體   English   中英

使用帶有打字稿的ES6符號

[英]Using ES6 Symbols with typescript

我正在嘗試運行這個簡單的代碼行 -

let FUNJECTOR_KEY = Symbol.for('funjector')

但我一直收到錯誤 - Cannot find name 'Symbol'. 我是打字稿的新手,所以我不確定是否需要包含一些內容?

在我的情況下,我不想使用這里解釋的poly填充 - 在typescript中使用es-6符號

TypeScript編譯器將TS轉換為JS。 TSC在es5模式下找不到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;
}

警告:某些類型檢查不適用於symbol 例如,您不能在接口上聲明計算為符號的屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM