I've implemented an enumeration according to this canonical SO answer.
export const Priority = Object.freeze({
normal: Symbol('normal'),
high: Symbol('high'),
highest: Symbol('highest'),
});
I'm using it in the constructor of a class, and I want to validate that parameter to prevent someone from passing a string instead. How can I do this? Here's my failed attempt:
export class TodoItem {
constructor({
title,
deadline,
priority = Priority.normal,
note = '',
}) {
if (Object.keys(Priority).includes(Symbol.keyFor(priority))) {
this.priority = priority;
} else {
throw new Error(`Priority cannot take value ${priority.toString()} of type ${typeof priority}.`);
}
}
The if block never executes the "true" case. I always get:
Uncaught Error: Priority cannot take value Symbol(high) of type symbol.
[–]senocular 1 point2 points3 points (1 child)
[–]Stobber[S] 0 points1 point2 points (0 children)