简体   繁体   English

在 typescript 中使用 arr.map(elem => dict[elem]) 时如何返回 null 而不是 undefined?

[英]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:我写了一个简单的 function 来根据查找字典 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.但是,当数组值在查找字典中不匹配时,我希望 function 返回null

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但我希望 output 成为

// ["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 (不确定它是否有所作为),是否有足够简单的方法来实现这一点?

Typescript REPL Typescript 回复

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):undefined的情况下,您可以使用无效合并运算符 ( ?? )解析null (并使用泛型类型参数从dict参数推断值的类型):

TS Playground TS游乐场

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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