Skip to content

Better typing support for ES2015 symbols #11736

Closed
@vdbwouter

Description

@vdbwouter

An interesting usage of ES2015's symbol is using it as a replacement for string/integer constants. An usage example would be:

let opAdd = Symbol('add')
let opSubtract = Symbol('subtract')

function calculate(operation: symbol, a: number, b: number) {
  if (operation === opAdd) {
    return a + b
  } else {
    // operation could be almost any symbol
    return a - b
  }
}

However, this causes the issue that you can't specify what symbols are accepted. This could be resolved by using string constants, for example:

function calculate(operation: 'add' | 'subtract', a: number, b: number) {
  if (operation === 'add') {
    return a + b
  } else {
    // operation *MUST* be 'subtract'
    return a - b
  }
}

I propose another option which would allow you to continue to use symbols instead of string constants: specify the accepted symbols in the type signature. It could look like this:

let opAdd = Symbol('add')
let opSubtract = Symbol('subtract')

function calculate(operation: opAdd | opSubtract, a: number, b: number) {
  if (operation === opAdd) {
    return a + b
  } else {
    // operation *MUST* be opSubtract
    return a - b
  }
}

This has the advantage of looking very similar to string constants but still allowing you to use symbols.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs ProposalThis issue needs a plan that clarifies the finer details of how it could be implemented.SuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions