将ES6符号与typescript一起使用
Using ES6 Symbols with typescript
我正在尝试运行这行简单的代码——
let FUNJECTOR_KEY = Symbol.for('funjector')
但我一直收到错误--Cannot find name 'Symbol'.
我是打字新手,所以我不确定是否需要包括一些内容?
在我的例子中,我不想使用这里解释的poly-fill——在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
上不起作用。例如,不能在接口上声明计算为符号的属性。
相关文章:
- 转义符不能与innerHTML一起使用
- Foreach无法在Typescript中工作
- 扩展SVGTextElement时出现Typescript Uncaught TypeError
- 为什么无法在TypeScript中导出类实例
- 如何将TypeScript对象转换为普通对象
- Angular 2.0 with JavaScript or TypeScript?
- 高亮显示与数组字符串一起使用时文本插件中断
- "实例范围”;TypeScript类的getter/setter
- 如何将js库与typescript一起使用
- 将 Sinon 与 Typescript 和接口一起使用
- 将ES6符号与typescript一起使用
- 如何将 TypeScript 与环回一起使用
- 如何将 Typescript 与原生 ES6 Promise 一起使用
- 如何使用 NPM 安装 socket.io 与 TypeScript 和 webpack 一起使用
- 声明与TypeScript一起使用的JS库
- 需要将fabricjs.d.ts与TypeScript一起使用的示例
- TypeScript可以和现有的JavaScript代码一起使用吗?
- 导入外部javascript库到Typescript中,以便与node一起使用
- 让TypeScript、Karma、RequireJS和Chai一起工作
- TypeScript为什么要把模块模式和原型模式混在一起?