Returning a Symbol in TypeScript

Viewed 228

The following example contains a function factory that returns a Symbol of type Bob. However, TypeScript seems to immediately forget the type of the return value and prevents me from assigning the return value to variable test one line later.

const bob: unique symbol = Symbol('bob')
type Bob = typeof bob

const factory = (): Bob => bob
const instance = factory()
const test: Bob = instance // Type 'symbol' is not assignable to type 'unique symbol'.

Iam aware an explicit type signature would solve this error:

const instance: typeof bob = factory();

or

const intance: Bob = factory();

Is there a way to fix this without modifying the variable instance to have an explicit type signature.

2 Answers

unique symbol is produced only from calling Symbol() or Symbol.for(), or from explicit type annotations.

That's why const instance = factory(); results in symbol

Docs

Related