能否用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
相关产品推荐
相关产品推荐

