TypeScript泛型联合类型中execute方法参数隐式any问题如何解决
问题原因
你遇到的隐式any报错是TypeScript对联合类型的同名方法参数推断的限制导致的:
你的Command<TArgs>是由ContextMenuCommand/SlashCommand/LegacyCommand<TArgs>组成的联合类型,三个子类型都定义了同名的execute方法但参数签名完全不同。TypeScript在推断对象字面量的方法参数时,不会先根据判别字段type: "LEGACY"收窄类型再推断参数,而是会先尝试合并所有execute的签名,合并失败就会触发参数推断失效,最终报隐式any错误。
你重命名execute之后,另外两个子类型没有对应方法,TS就会先根据type字段收窄到LegacyCommand类型,参数自然可以正常推断。
解决方案
最稳定的解决方式是给createCommand添加分类型重载,让TypeScript在推断参数前先匹配对应命令类型的重载,避免直接处理联合类型:
// 新增三个重载,分别对应三种命令类型 export function createCommand(command: ContextMenuCommand): ContextMenuCommand export function createCommand(command: SlashCommand): SlashCommand export function createCommand<TArgs = void>(command: LegacyCommand<TArgs>): LegacyCommand<TArgs> // 原有实现保持不变 export function createCommand<TArgs = void>(command: Command<TArgs>) { return command }
修改后你传入type: "LEGACY"的对象时,TS会自动匹配第三个重载,直接按LegacyCommand类型推断,execute的参数就能正常识别为Message类型,不需要手动声明参数类型。
如果你不想修改createCommand的定义,也可以在调用时显式指定泛型:
export default createCommand<void>({ type: "LEGACY", name: "", description: "", execute(message) { // message 会被自动推断为 Message 类型 }, })
内容的提问来源于stack exchange,提问作者user16985789
相关产品推荐
相关产品推荐

