Typescript: Make Symbol.* (e.g. Symbol.iterator) unique symbols

Created on 3 Oct 2018  路  4Comments  路  Source: microsoft/TypeScript

Search Terms

Suggestion

Use this:

declare function Symbol (x?: string | number): symbol

declare namespace Symbol {
  const prototype: symbol
  const iterator: unique symbol
}

Or this:

interface SymbolConstructor {
  (x?: string | number): symbol
  readonly prototype: symbol
  readonly iterator: unique symbol
}

declare var Symbol: SymbolConstructor

Instead of this:

interface SymbolConstructor {
  (x?: string | number): symbol
  readonly prototype: symbol
  readonly iterator: symbol
}

declare var Symbol: SymbolConstructor

Use Cases

Right now, I can do this for custom unique symbol:

const foo = Symbol() // unique symbol
const bar: typeof foo = foo

const baz: {
    [foo]: number
} = {
    [bar]: 123
}

But not for Symbol.*

// Expecting 'typeof Symbol.iterator' but received 'symbol'
const iterator: typeof Symbol.iterator = Symbol.iterator

// This is not working
const iterable: Iterable<number> = {
  * [iterator] () {
    yield * [0, 1, 2, 3]
  }
}

Checklist

My suggestion meets these guidelines:

  • [x] This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • [x] This wouldn't change the runtime behavior of existing JavaScript code
  • [x] This could be implemented without emitting different JS based on the types of the expressions
  • [x] This isn't a runtime feature (e.g. new expression-level syntax)

Playground Link (This also works)

Related Issue

Bug Committed

Most helpful comment

This is something we plan to do, but requires us to support "typesVersions" on DefinitelyTyped so that we can address the forward-declaration of Symbol.iterator, etc. in the type definitions for NodeJS, core-js, and es6-shim.

All 4 comments

@rbuckton what are your thoughts on this?

This is something we plan to do, but requires us to support "typesVersions" on DefinitelyTyped so that we can address the forward-declaration of Symbol.iterator, etc. in the type definitions for NodeJS, core-js, and es6-shim.

https://github.com/Microsoft/TypeScript/pull/24738 also works around the old-lib issue by considering any symbols under the global Symbol constructor as unique symbols.

https://github.com/microsoft/TypeScript/pull/24738 would fix this in a manner that鈥檚 compatible with old .d.ts files.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nitzantomer picture nitzantomer  路  135Comments

chanon picture chanon  路  138Comments

jonathandturner picture jonathandturner  路  147Comments

RyanCavanaugh picture RyanCavanaugh  路  205Comments

blakeembrey picture blakeembrey  路  171Comments