问题描述
我有一个组件使用了外部项目中的另一个组件。如何在没有重复类型的情况下在外部组件中生成流类型?
例如:
import {ExternalComponent} from '@npm-component/another-component';
type CurrentComponentType = {|
data: {
count: number,items: [{code: string,descroption: string}]
}
|};
export CurrentComponent = ({data}: CurrentComponentType) => {
const onClick = () => {}
return <ExternalComponent data={data} onClick={onClick}/>;
}
目前,我在外部组件中复制流类型
type ExternalComponentType = {|
data: {
count: number,descroption: string}]
}
|};
export ExternalComponent = ({data}: ExternalComponent) => {
const onClick = () => {}
return data.items.map(({code}) => <span>{code}</span>);
}
例如我想要的
type ExternalComponentType = GenerateTypeHere;
export ExternalComponent = ({data}: ExternalComponent) => {
const onClick = () => {}
return data.items.map(({code}) => <span>{code}</span>);
}
解决方法
这取决于您要从中导入的库是否确实导出了流类型。让我们假设它是为了回答问题。
如果他们这样做,他们的代码看起来像这样
// @flow
export type ComponentProps = {};
export default Component = () => ...
然后在你的代码中你可以像这样导入它
// @flow
import Component,{ type ComponentProps } from '@npm-component/another-component';
// Or if you want to import just the type on a line
import type { ComponentProps } from '@npm-component/another-component';
type CurrentComponentType = {
...ComponentProps,a: string,// If you want to extend the props with more functionality
};
export const CurrentComponent = ({ data }: CurrentComponentType) => {
const onClick = () => {}
return <ExternalComponent data={data} onClick={onClick}/>;
}