javascript - 寻找一种将 x 或 x[] 转换为 x[] 的单线器
问题描述
我正在寻找可以替换以下功能的简短有效的普通 TypeScript 单行代码:
function arrayOrMemberToArray<T>(input: T | T[]): T[] {
if(Arrary.isArray(input)) return input
return [input]
}
将上述逻辑塞进一个单行三元运算符是非常混乱的,并且在与其他操作链接时很难遵循:
const y = (Array.isArray(input) ? input : [input]).map(() => { /* ... */}) // Too messy
Array.concat
在浏览器控制台中工作正常,但 TS 不允许:
const x: number | number[] = 0
const y = [].concat(x)
Error:(27, 21) TS2769: No overload matches this call.
Overload 1 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
Argument of type 'number' is not assignable to parameter of type 'ConcatArray<never>'.
Overload 2 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
Argument of type 'number' is not assignable to parameter of type 'ConcatArray<never>'.
解决方案
由于空数组文字,该concat
解决方案不会进行类型检查。你需要写
const arr = ([] as number[]).concat(input);
或者,您可以使用flat
:
const arr = [input].flat();
这不仅更短而且更可取,因为它不依赖于输入的concat-spreadable 属性,而是实际检查数组。
推荐阅读
- sql - 在 SQL Server 中使用 Merge 语句
- r - R中的虚拟变量,结果全部为0
- ios - 字符串:字符串?数组而不是字符串:字符串数组在 SwiftUI 视图中中断 ForEach?
- arrays - 如何在 Swift 中将 Nil 对象添加到对象数组中
- java - 如何使用预签名 URL 限制 AWS S3 存储桶中对象的上传大小?
- scala - 字节数组到Json对象的高效解析
- java - 在 Java 中将 HTML 字符串转换为 PDF 字节数组
- wordpress - 是否可以将搜索结果用作 $args 的一部分?
- java - Android Firebase 手机认证 - 在华为手机上第二次未发送代码
- javascript - 我的函数有什么问题,它不断抛出非函数错误?