如何为属性均为不同参数函数的对象创建泛型type或interface
问题原因
你之前的写法不生效,是因为函数层面的泛型<T extends any>(...args: T[]) => void强制要求每个函数的参数是任意类型任意长度,和你实际定义的函数固定参数类型不兼容。而直接用Function作为值类型确实会丢失所有类型提示。
解决方案
可以按以下两种场景选择实现方式:
场景1:定义具体的action聚合对象,需要保留完整代码补全
先定义基础约束类型,再通过泛型工具函数实现约束+自动类型推导:
// 基础约束:所有值都是接收任意参数、返回void的函数 type ActionAggregator = Record<string, (...args: any[]) => void> // 泛型工具函数:仅接收符合约束的对象,返回对象的精确类型 const defineActionAggregator = <T extends ActionAggregator>(aggregator: T) => aggregator
使用示例:
const actionsPost = defineActionAggregator({ likePost: (id: number) => dispatch({type: Actions.like, payload: {id}}), addPost: (title: string, body: string) => dispatch({type: Actions.add, payload: {title, body}}), updatePost: (id: number, title: string, body: string) => dispatch({type: Actions.add, payload: {id, title, body}}), }) const actionsComment = defineActionAggregator({ likeComment: (id: number) => dispatch({type: Actions.like, payload: {id}}), addComment: (postId: number, body: string) => dispatch({type: Actions.comment, payload: {postId, body}}), })
这种写法下,actionsPost.likePost 调用时会有完整的参数类型提示,如果你传入的对象里有非函数类型的值,TypeScript会直接抛出类型错误。
场景2:需要接收任意action聚合对象作为参数
直接使用定义好的ActionAggregator作为参数类型即可:
function registerActions(aggregator: ActionAggregator) { // 通用逻辑实现 } // 可正常传入所有符合结构的聚合对象 registerActions(actionsPost) registerActions(actionsComment)
内容的提问来源于stack exchange,提问作者HolandesVoador
相关产品推荐
相关产品推荐

