在打字稿中使用 arr.map(elem => dict[elem]) 时如何 return null 而不是 undefined ?
How to return null instead of undefined when using arr.map(elem => dict[elem]) in typescript?
我写了一个简单的函数来根据查找字典对象替换数组中的值:
// typescript
function recode(arr: any[], dict: Record<string, string> ) {
return arr.map(el => dict[el])
}
它按预期工作。但是,当数组值在查找字典中不匹配时,我希望函数 return 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]
但我希望输出为
// ["purple", "red", "orange", null]
考虑到我使用的是 typescript(不确定它是否有所作为),是否有足够简单的方法来实现此目的?
您可以使用 nullish coalescing operator (??
) to resolve null
in cases of undefined
(and use a generic 类型参数从 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);
我写了一个简单的函数来根据查找字典对象替换数组中的值:
// typescript
function recode(arr: any[], dict: Record<string, string> ) {
return arr.map(el => dict[el])
}
它按预期工作。但是,当数组值在查找字典中不匹配时,我希望函数 return 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]
但我希望输出为
// ["purple", "red", "orange", null]
考虑到我使用的是 typescript(不确定它是否有所作为),是否有足够简单的方法来实现此目的?
您可以使用 nullish coalescing operator (??
) to resolve null
in cases of undefined
(and use a generic 类型参数从 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);