TypeScript如何避免接口继承实现时函数对象参数类型重复声明
方案1:修正Parameters工具类型的用法
你之前类型识别失败是因为两个写法错误:
- TypeScript 内置的工具类型是
Parameters(复数,末尾带s),不是单数Parameter - 访问接口的方法类型需要用索引访问语法
Interface['methodName'],不能用点号访问
只需要将实现类的参数类型改为Parameters<ComposedServiceInterface['doesThings']>[0]即可,不需要额外导入其他类型:
// src/implementations/ComposedServiceImplementation.ts import { ComposedServiceInterface } from "../domain/ComposedServiceInterface"; export class ComposedServiceImplementation implements ComposedServiceInterface { doesThings( args: Parameters<ComposedServiceInterface["doesThings"]>[0] ): boolean { // 直接使用args,所有字段的类型都会自动推导 console.log(args.awesomeFieldName); return true; } hello(): string { return "hello"; } }
后续如果需要修改doesThings的入参结构,只需要修改ServiceInterface中的定义,所有实现类的参数类型会自动同步,不需要手动修改。
方案2:在组合接口文件内导出衍生参数类型
如果觉得长串的Parameters写法可读性差,可以直接在ComposedServiceInterface所在的文件内导出对应的参数类型,实现侧仅需要从同一个文件导入即可,不需要跨文件依赖原始接口的定义:
// src/domain/ComposedServiceInterface.ts import { ServiceInterface } from "./ServiceInterface"; export type ComposedServiceInterface = ServiceInterface & { hello: () => string }; // 直接在当前文件导出参数类型,供实现侧使用 export type DoesThingsParameter = Parameters<ComposedServiceInterface['doesThings']>[0];
实现类的代码简化为:
// src/implementations/ComposedServiceImplementation.ts import { ComposedServiceInterface, DoesThingsParameter } from "../domain/ComposedServiceInterface"; export class ComposedServiceImplementation implements ComposedServiceInterface { doesThings(args: DoesThingsParameter): boolean { return true; } hello(): string { return "hello"; } }
两种方案都满足你仅依赖ComposedServiceInterface相关定义的要求,不需要重复编写参数结构,也不需要额外导入原始接口内的类型。
内容的提问来源于stack exchange,提问作者YesYouKen
相关产品推荐
相关产品推荐

