TypeScript中使用arr.map(elem => dict[elem])时如何返回null而非undefined
简洁实现方案:用空值合并运算符替换undefined为null
你可以利用TypeScript支持的**空值合并运算符(??)**来简洁地实现这个需求,它专门用于处理null/undefined的场景,比传统条件判断更简洁直观。
修改后的函数如下:
function recode(arr: string[], dict: Record<string, string>): (string | null)[] { return arr.map(el => dict[el] ?? null); }
为什么这个方案可行?
- 当数组元素
el在字典dict中存在对应键时,dict[el]会返回匹配的字符串值; - 当
el不存在于字典中时,dict[el]会返回undefined,此时??运算符会触发右侧的null,把结果替换成你期望的null; - 我们还调整了函数的返回类型注解,从原来的
(string | undefined)[]明确为(string | null)[],让TypeScript的类型检查更精准,也符合你的输出预期。
用你的测试代码验证:
const myArr: string[] = ['eggplant', 'tomato', 'carrot', 'cabbage']; const myDictionary: Record<string, string> = { eggplant: 'purple', tomato: 'red', carrot: 'orange' }; console.log(recode(myArr, myDictionary)); // 输出:["purple", "red", "orange", null]
如果你的数组元素可能包含非字符串类型(比如保留原来的any[]参数),也可以用Object.prototype.hasOwnProperty做更严谨的键存在性判断,但对于你当前的场景,??已经足够简洁且完全满足需求。
内容的提问来源于stack exchange,提问作者Emman
相关产品推荐
相关产品推荐

