You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript如何去除重复类型并将返回的never替换为void

解决方案

你的ReplaceNever工具类型不生效的核心原因是 TypeScript 的分布式条件类型特性:当条件类型的入参是裸类型参数且为never时,条件类型会直接返回never,不会执行后续的判断逻辑。你只需要把条件两侧包装成元组,关闭分布式特性即可修复问题。

修正后的完整代码如下:

// 关闭分布式条件类型的ReplaceNever
type ReplaceNever<T> = [T] extends [never] ? void : T;

type GetCommandParamTypes<T extends Command<unknown, unknown>> = 
    T extends Command<infer IO, infer A> ?
    [IO, ReplaceNever<Exclude<A, IO>>] :
    never;

验证结果符合预期:

// 单泛型实现类场景
type type5 = GetCommandParamTypes<TypeACommand>; // [string, void]
// 双泛型实现类场景
type type3 = GetCommandParamTypes<MixedTypeCommand>; // [string | number, Function]
// 直接传入Command泛型场景
type type1 = GetCommandParamTypes<Command<string>>; // [string, void]

如果你不想单独定义ReplaceNever,也可以直接把判断逻辑合并到工具类型中:

type GetCommandParamTypes<T extends Command<unknown, unknown>> = 
    T extends Command<infer IO, infer A> 
    ? [IO, [Exclude<A, IO>] extends [never] ? void : Exclude<A, IO>] 
    : never;

内容的提问来源于stack exchange,提问作者james。

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 15:24:02