![](/img/trans.png)
[英]How to extract a function out of arr.map(elem => dict[elem])?
[英]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 (不確定它是否有所作為),是否有足夠簡單的方法來實現這一點?
在undefined
的情況下,您可以使用無效合並運算符 ( ??
)解析null
(並使用泛型類型參數從dict
參數推斷值的類型):
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.