Skip to content

Better typing support for ES2015 symbols #11736

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Closed
vdbwouter opened this issue Oct 19, 2016 · 1 comment · Fixed by #15473
Closed

Better typing support for ES2015 symbols #11736

vdbwouter opened this issue Oct 19, 2016 · 1 comment · Fixed by #15473
Labels
Needs Proposal This issue needs a plan that clarifies the finer details of how it could be implemented. Suggestion An idea for TypeScript

Comments

@vdbwouter
Copy link

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.

@mhegazy
Copy link
Contributor

mhegazy commented Oct 19, 2016

Relevant details can be found in #2012

@mhegazy mhegazy added Suggestion An idea for TypeScript Needs Proposal This issue needs a plan that clarifies the finer details of how it could be implemented. labels Oct 19, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
# for free to subscribe to this conversation on GitHub. Already have an account? #.
Labels
Needs Proposal This issue needs a plan that clarifies the finer details of how it could be implemented. Suggestion An idea for TypeScript
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants