In JavaScript we have global symbol on the Symbol object, such as Symbol.iterator and Symbol.match.
I can assign the property by erasing the type to any, however TypeScript doesn’t recognise it.
// Define Symbol.hello
(Symbol as any).hello = Symbol("hello");
// Try using it later:
Symbol.hello;
// TypeScript error: Property 'hello' does not exist on type 'SymbolConstructor'.ts(2339)
How do I add my property to Symbol in a way that makes TypeScript happy?
You can declare your property on the SymbolConstructor interface:
declare global {
interface SymbolConstructor {
readonly hello: symbol;
}
}
You can now define your property:
// Define Symbol.hello
(Symbol as { hello: symbol }).hello = Symbol("hello");
// TypeScript is now happy:
Symbol.hello;