我想试试 toSpliced() 方法
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'
Argument of type '"hi"' is not assignable to parameter of type '1 | 2'
我尝试复制数组:
const copiedA = [...a] //or const copiedA = a.map(x => x)
或键入assert:
const b = a.toSpliced(0, 1, 'hi') as any
但这些都不起作用。有办法避免这种情况吗?
的类型 a 是 readonly [1, 2] .
a
readonly [1, 2]
如果你想把它当作其他东西来处理,你可以使用 as .
as
const b = (a as readonly any[]).toSpliced(0, 1, 'hi')
或者两行
const anyArr: readonly any[] = a const c = anyArr.toSpliced(0, 1, 'hi')
您应该更换 any 用任何合适的东西。
any