组件库 TypeScript 类型导出最佳实践
组件库如何正确导出 TypeScript 类型声明?如何在 package.json 中配置 types/typings 字段?d.ts 文件的生成方式有哪些?如何为 HOC/泛型组件导出类型?
回答
我是大山
package.json 设置 types:'dist/index.d.ts'。生成: tsc --declaration 或 rollup-plugin-dts。目录: dist/ 输出 esm/cjs + 对应 .d.ts。export type: export type { ButtonProps }。HOC: function withTheme
(Comp: React.ComponentType
): React.FC<P & ThemeProps>。泛型: function List(props: ListProps): JSX.Element。forwardRef: const Button = forwardRef<HTMLButtonElement, ButtonProps>((props, ref)=>{...})。注意: 联合类型不重复导出;paths 别名用 relative 路径。