如何在不复制类型的情况下使用toSpliced()?

问题描述 投票:0回答:1

我想尝试一下

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

但这些都不起作用。有没有办法避免这种情况?

arrays typescript splice
1个回答
0
投票

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')
© www.soinside.com 2019 - 2024. All rights reserved.