Using undefined as key in object

Viewed 845

I use an object to map one value to another, e.g.

const wordToNumber = {
  one: 1,
  two: 2,
  three: 3,
}

But also I have a special case that when user tries to get a value by key undefined I want it to return 1 as well.

So I change the object to this:

const wordToNumber = {
  one: 1,
  two: 2,
  three: 3,
  [undefined]: 1,
}

And it works as expected in playground:

enter image description here

But TS complains on undefined key: TS2464: A computed property name must be of type 'string', 'number', 'symbol', or 'any'.

And I'm wondering is there anything wrong with using undefined as an object key or it's fine and I can just hide the complaint with ts-ignore?

3 Answers

Have you tried removing the square brackets. This worked for me in JSFiddle

const wordToNumber = {
    one: 1,
    two: 2,
    three: 3,
    undefined: 1,
}

alert(wordToNumber["one"])
alert(wordToNumber[undefined])

Maybe you need to use map in this case (with get and set)?

const m = new Map();
m.set(undefined, "test");
console.log(m.get(undefined));

There are multiple ways to do this. I would do it like this:

const wordToNumber = (word) => {    
    if (typeof word !== "string") {
        return "1";
    }
    
    return {
        one: 1,
        two: 2,
        three: 3,
    }[word];
}

wordToNumber("one");

This returns "1" if the word is not a string, instead of looking for undefined specifically.

Related