Closed
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.