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

TypeScript中如何用泛型参数约束泛型参数以复用类型?

消除TypeScript重复泛型类型的方案

你可以通过新增一个泛型参数来指定P的约束类型,从而复用核心的类型逻辑,避免重复定义。优化后的代码如下:

import { ComponentPropsWithRef, ElementType } from "react";

interface PackshotPropsBase {
  a: string
}

interface PackshotPropsWeb {
  b: string
}

// 通用泛型类型,新增B参数作为P的基类型约束
export type ElementAndPackshotPropsGeneric<T extends ElementType, B, P extends B> = Omit<
    ComponentPropsWithRef<T>,
    keyof P
> &
    P;

// 基于通用类型派生原来的两个类型
export type ElementAndPackshotProps<T extends ElementType, P extends PackshotPropsBase> = ElementAndPackshotPropsGeneric<T, PackshotPropsBase, P>;
export type ElementAndPackshotPropsWeb<T extends ElementType, P extends PackshotPropsWeb> = ElementAndPackshotPropsGeneric<T, PackshotPropsWeb, P>;

说明

核心逻辑被封装在ElementAndPackshotPropsGeneric中,通过第三个泛型参数B来动态指定P的约束类型。原来的两个类型只需要传递对应的基类型(PackshotPropsBase或PackshotPropsWeb),就能复用相同的类型组合逻辑,彻底消除代码重复。后续如果需要新增类似的类型,只需基于这个通用类型派生,无需重复编写重复的Omit与交叉类型逻辑。

内容的提问来源于stack exchange,提问作者Mr. Robot

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 09:54:21