我有一个可以选择接受数组的函数。我还有其他变量可能未定义,但如果定义了它们,我想从中创建一个数组:
function test(array?: string[]) {
console.log(array);
}
let value: string | undefined;
value = 'abc';
const temp = value ? [value] : undefined; // Shorthand?
test(temp)
是否有一种使用字符串
数组创建temp
变量或传递undefined
的简便方法?我尝试执行以下操作但没有实现:
// If value is 1, true, or 'some string' it will take that value not the array
const temp = value && [value];
// Passes back an empty array if value is undefined
const temp = [value].filter(Boolean),
最佳答案
正如评论中所指出的,只需为此创建一个辅助函数:
const arrOrUndef = <T,>(val: T | undefined): T[] | undefined => val !== undefined ? [val] : undefined;
然后只需使用:
let value: string | undefined = 'abc';
test(arrOrUndef(value))
另外,感谢 pilchard在注释中指出,最好使用泛型,而不仅仅是问题中的 string
类型或 any
类型。另外,JDB请注意,您必须使用 !== undefined
,而不是简单地检查虚假值(如原始问题那样)。
关于javascript - 有条件地根据可选值创建数组的简写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75667797/