用 typescript 接口统一抽离 props 类型是最自然可靠的复用方式,定义在独立类型文件中,支持扩展、泛型及精确提取,避免冗余与维护不一致。

多个组件需要使用相同的 Props 定义时,直接复制粘贴类型声明不仅冗余,还容易导致后续维护不一致。用 TypeScript 接口(interface)统一抽离 Props 类型,是最自然、最可靠的复用方式。
定义一个共享的 Props 接口
在独立的类型文件(如 types/shared.ts 或 components/types.ts)中声明接口,明确描述公共字段及其类型:
export interface ButtonProps {
label: string;
size?: 'small' | 'medium' | 'large';
disabled?: boolean;
onClick?: () => void;
}
这样所有用到该结构的组件都能导入并复用,无需重复书写。
完整的Galileo AI平台 TypeScript/JS SDK 参考,用于评估、观察和保护 GenAI 应用。适用于构建 Node.js 或 TypeScript 项目。
在不同组件中导入并使用
每个组件只需 import 接口,并将其作为自己的 Props 类型:
-
PrimaryButton.tsx:
const PrimaryButton: React.FC<buttonprops> = ({ label, size = 'medium', ... }) => { ... }</buttonprops> -
OutlineButton.tsx:
interface OutlineButtonProps extends ButtonProps { variant?: 'default' | 'danger'; }—— 可基于原接口扩展新字段 - 函数组件也可直接用
React.FC<buttonprops></buttonprops>或更推荐的(props: ButtonProps) => JSX.Element,避免隐式 children 问题
配合泛型支持更灵活的复用
当多个组件共用结构但部分字段类型不同时,可把接口设为泛型:
export interface ActionCardProps<t unknown> {
title: string;
actionLabel: string;
onAction: (data: T) => void;
data?: T;
}</t>
使用时指定具体类型:
-
ActionCardProps<user></user>用于用户操作卡片 -
ActionCardProps<product></product>用于商品操作卡片
避免常见陷阱
- 不要用
type替代interface做纯对象结构定义——接口支持声明合并(declaration merging),更适合长期演进的共享类型 - 避免在接口里写运行时逻辑(如默认值、条件判断),它只负责类型约束
- 如果某组件仅复用部分字段,不要强行全量继承,可搭配
Omit<buttonprops></buttonprops>或Pick<buttonprops></buttonprops>精确提取










