toSpliced()
方法:
const a = [1, 2] as const
const b = a.toSpliced(0, 1, 'hi')
这会产生错误:
Argument of type '"hi"' is not assignable to parameter of type '1 | 2'
我尝试复制数组:
const copiedA = [...a] //or
const copiedA = a.map(x => x)
或输入断言:
const b = a.toSpliced(0, 1, 'hi') as any
但这些都不起作用。有没有办法避免这种情况?
a
的类型是[1, 2]
。
如果你想把它当作其他东西,你可以使用
as
来投射它。
const b = (a as readonly any[]).toSpliced(0, 1, 'hi')
分两行
const anyArr: readonly any[] = a
const c = anyArr.toSpliced(0, 1, 'hi')