[SOLVED] How to return null instead of undefined when using arr.map(elem => dict[elem]) in typescript?

Issue

I wrote a simple function to replace values in an array according to a look-up dictionary object:

// typescript
function recode(arr: any[], dict: Record<string, string> ) {
    return arr.map(el => dict[el])
}

It works as expected. However, I want the function to return null when array values have no match in the look-up dictionary.

So right now if I do:

// array input
const myArr: string[] = ['eggplant', 'tomato', 'carrot', 'cabbage'];

// look-up dictionary
const myDictionary: Record<string, string> = {
    eggplant: 'purple',
    tomato: 'red',
    carrot: 'orange'
};

function recode(arr: any[], dict: Record<string, string> ) {
    return arr.map(el => dict[el])
}

// calling recode()
recode(myArr, myDictionary) 
// returns 
// ["purple", "red", "orange", undefined] 

But I want the output to be

// ["purple", "red", "orange", null] 

Is there a simple enough way to achieve this, considering that I’m using typescript (not sure it makes a difference)?

Typescript REPL

Solution

You can use the nullish coalescing operator (??) to resolve null in cases of undefined (and use a generic type parameter to infer the type of values from the dict parameter):

TS Playground

const myArr: string[] = ['eggplant', 'tomato', 'carrot', 'cabbage'];

const myDictionary: Record<string, string> = {
    eggplant: 'purple',
    tomato: 'red',
    carrot: 'orange'
};

function recode <T extends Record<string, any>>(
  arr: readonly string[],
  dict: T,
): (T[keyof T] | null)[] {
    return arr.map(el => dict[el] ?? null);
}

const result = recode(myArr, myDictionary); // (string | null)[]
console.log(result);

Answered By – jsejcksn

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.