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

能否用Interface重写TypeScript的WithChildren辅助类型?

用Interface重写WithChildren辅助类型当然可行!

绝对没问题,你完全可以把原有的WithChildren类型用interface来改写,效果和原来的交叉类型一模一样,甚至在有些场景下会让代码的结构感更强。

具体实现方式

直接利用TypeScript接口的泛型和继承特性就能实现:

interface WithChildren<T = {}> extends T {
  children?: React.ReactNode;
}

这里通过extends T把传入的泛型类型和children属性合并,和原来的T & { children?: React.ReactNode }交叉类型逻辑完全等价。

结合你的Card组件使用

你可以像原来一样用它来定义CardProps:

type CardProps = WithChildren<{ title: string }>;

function Card({ title, children }: CardProps) {
  return (
    <>
      <h1>{title}</h1>
      {children}
    </>
  );
}

或者如果你更喜欢全程用interface的风格,也可以直接让CardProps继承WithChildren:

interface CardProps extends WithChildren {
  title: string;
}

这样写出来的代码同样能正确约束组件的props,效果和之前完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 20:18:08