简体   繁体   中英

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

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM