Closed acopalipsis closed 8 years ago
The native Symbol
should start with uppercase. The type definitions use uppercase as well. Can you share more details about the error please?
let id: symbol = Symbol.for('some-id'); // Symbol is constructor which retutn type symbol
typeof id === "symbol"; // true
String === string, Number === number, Symbol === symbol
Symbol
can be used to declare global and local symbols:
Symbol.for("foo"); // create a new global symbol
Symbol.for("foo"); // retrieve the already created symbol
// Same global symbol, but not locally
Symbol.for("bar") === Symbol.for("bar"); // true
Symbol("bar") === Symbol("bar"); // false
// The key is also used as the description
var sym = Symbol.for("mario");
sym.toString(); // "Symbol(mario)"
More info here.
InversifyJS is designed to use local symbols:
let TYPES = {
Katana: Symbol("IKatana"),
Ninja: Symbol("INinja"),
Shuriken: Symbol("IShuriken")
};
@injectable()
class Ninja implements INinja {
private _katana: Katana;
private _shuriken: Shuriken;
public constructor(
@inject(TYPES.Katana) katana: Katana,
@inject(TYPES.Shuriken) shuriken: Shuriken
) {
this._katana = katana;
this._shuriken = shuriken;
}
public fight() { return this._katana.hit(); };
public sneak() { return this._shuriken.throw(); };
}
A full example is available here.
https://www.typescriptlang.org/play/#src=let%20a%3A%20Symbol%3B%0Alet%20b%3A%20symbol%3B see that red Symbol? in .ts.d validation of the type Symbol.. but the compiler is yelling that this is a mistake, because there is no type Symbol is symbol.
When you select a compilation target, TypeScript imports a file named lib.d.ts
. This file delcares all the native JavaScript objects. The Symbol
object is not recognized by typescript unless you target ES6. But if you add the InversifyJS type definitions:
/// <reference path="node_modules/inversify/type_definitions/inversify/inversify.d.ts" />
You will be able to target ES5 and the Symbol
should be declared.
You are right I compile es6. It was easier for me to .ts.d edit Symbol on the symbol.
In native js has a type
symbol
. But You have to .ts.d specified the typeSymbol
? It's a typo?