如何在对象字面量中声明方法的类型?(异步函数场景)
解决方案
有几种方式可以给对象字面量中的myTest方法指定Props['onRequest']类型,以下是具体实现:
方法1:为整个对象定义类型约束
先声明包含所有属性的对象类型,明确myTest的类型为Props['onRequest'],再用这个类型约束myObj:
interface Props { loading?: boolean | undefined; separator?: 'cell' | 'none'; onRequest?: (requestProp: { pagination: { sortBy: string; descending: boolean; page: number; rowsPerPage: number; }; filter: string; }) => void; } // 定义对象的完整类型 interface MyObjType { myTest: Props['onRequest']; id: number; result: string; } const myObj: MyObjType = { async myTest({ pagination }) { let $id = this.id; // 执行await逻辑 await new Promise(resolve => setTimeout(resolve, 1000)); console.log($id, pagination); }, id: 521, result: '', };
方法2:直接给方法标注类型
在对象字面量中,直接为myTest指定类型。注意:异步函数返回Promise<void>,而Props['onRequest']要求返回void,这在TypeScript中是兼容的,因为异步函数的返回值会被自动忽略:
interface Props { loading?: boolean | undefined; separator?: 'cell' | 'none'; onRequest?: (requestProp: { pagination: { sortBy: string; descending: boolean; page: number; rowsPerPage: number; }; filter: string; }) => void; } const myObj = { // 直接指定方法类型,用Parameters提取参数结构避免重复定义 myTest: async function({ pagination }: Parameters<Props['onRequest']>[0]) { let $id = this.id; await new Promise(resolve => setTimeout(resolve, 1000)); console.log($id, pagination); } as Props['onRequest'], id: 521, result: '', };
方法3:使用类型别名简化复用
如果需要多次复用这个函数类型,可以先给Props['onRequest']起一个别名:
interface Props { loading?: boolean | undefined; separator?: 'cell' | 'none'; onRequest?: (requestProp: { pagination: { sortBy: string; descending: boolean; page: number; rowsPerPage: number; }; filter: string; }) => void; } // 类型别名,简化后续引用 type OnRequestFn = Props['onRequest']; const myObj = { myTest: async function({ pagination }: Parameters<OnRequestFn>[0]) { let $id = this.id; await new Promise(resolve => setTimeout(resolve, 1000)); console.log($id, pagination); } as OnRequestFn, id: 521, result: '', };
内容的提问来源于stack exchange,提问作者M.A.T
相关产品推荐
相关产品推荐

