vue3+ts报错:A spread argument must either have a tuple type or be passed to a rest parameter.ts(2556)?

问题:ts报错
A spread argument must either have a tuple type or be passed to a rest parameter.ts(2556)
(parameter) rest: Parameters<KeyMap[K]>

代码:

<script lang="ts" setup>

type KeyMap = {
    loading: () => unknown
    play: (duration: number) => unknown
}

type EmitsType = {
    [K in keyof KeyMap]: Parameters<KeyMap[K]>
}

const emit = defineEmits<EmitsType>()

const handleEmit = <K extends keyof KeyMap>(event: K, ...rest: Parameters<KeyMap[K]>) => {
    emit(event, ...rest)
}
</script>

vue版本 3.3.4, node环境 16.13.0 vscode/ts版本 5.1.3 volar版本:1.8.2

阅读 3.8k
1 个回答

看了下你的代码没问题,这是typescript不兼容导致的,升级 TypeScript 版本到最新,或者考虑不使用展开操作符,而是将参数直接传递给 emit() 函数即可。例如这样:

const emit = defineEmits<EmitsType>()

const handleEmit = <K extends keyof KeyMap>(event: K, ...rest: Parameters<KeyMap[K]>) => {
    emit(event, rest)
}

个人认为升级版本的解决方法最容易。

_

更新一下这个回答:
Parameters<KeyMap[K]>改为元组类型,或者将...rest传递给rest参数试试。具体代码如下:

const handleEmit = <K extends keyof KeyMap>(event: K, ...rest: Parameters<KeyMap[K]>[]) => {
    emit(event, ...rest)
}

或者:

const handleEmit = <K extends keyof KeyMap>(event: K, rest: Parameters<KeyMap[K]>) => {
    emit(event, rest)
}
推荐问题
logo
Microsoft
子站问答
访问
宣传栏