-
Notifications
You must be signed in to change notification settings - Fork 13.1k
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 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.
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