-
Notifications
You must be signed in to change notification settings - Fork 13k
Closed
Labels
Needs ProposalThis issue needs a plan that clarifies the finer details of how it could be implemented.This issue needs a plan that clarifies the finer details of how it could be implemented.SuggestionAn idea for TypeScriptAn idea for TypeScript
Description
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 symbol
s instead of string constants: specify the accepted symbol
s 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 symbol
s.
svieira, GoToLoop, sebald and NoelAbrahams
Metadata
Metadata
Assignees
Labels
Needs ProposalThis issue needs a plan that clarifies the finer details of how it could be implemented.This issue needs a plan that clarifies the finer details of how it could be implemented.SuggestionAn idea for TypeScriptAn idea for TypeScript