Typescript 通用以保留参数类型

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

我有一个带有任何参数的函数类型,但没有任何警告和提示。

type TThunkAction = (...payload: any) => (dispatch: () => void) => void

const action: TThunkAction = (id: number, text: string) => (dispatch) => {}
action('123', false) // not warning

我可以将参数用作单个对象:

type TThunkAction<TPayload = any> = (payload?: TPayload) => (dispatch: () => void) => void

const action: TThunkAction<{id: number, text: string}> = ({id, text}) => (dispatch) => {}
action({id: 123, ... // strong types

但我想使用类似“剩余参数”的东西。有什么办法可以做到这一点吗?

typescript generics arguments
1个回答
0
投票

我不完全确定我理解你想要做什么,但如果你希望能够指定函数的多个参数的类型,你可以这样做:

type TThunkAction<TArgs extends unknown[]> = (...payload: TArgs) => (dispatch: () => void) => void

const action: TThunkAction<[number, string]> = (id, text) => (dispatch) => {}
action('123', false) // warning

打字稿游乐场

© www.soinside.com 2019 - 2024. All rights reserved.