繁体   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?

我写了一个简单的 function 来根据查找字典 object 替换数组中的值:

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

它按预期工作。 但是,当数组值在查找字典中不匹配时,我希望 function 返回null

所以现在如果我这样做:

// 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] 

但我希望 output 成为

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

考虑到我使用的是typescript (不确定它是否有所作为),是否有足够简单的方法来实现这一点?

Typescript 回复

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

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