我正在尝试为.d.ts
的{{1}}文件添加类型定义,如下所示:
React.FunctionComponent
从'react'导入React; 从'd3-hierarchy'导入{TreeLayout,HierarchyPointNode,HierarchyNode};
我想出了这种方法:
Tree.propTypes = {
root: PropTypes.object.isRequired,
children: PropTypes.func,
top: PropTypes.number,
left: PropTypes.number,
className: PropTypes.string,
size: PropTypes.arrayOf(PropTypes.number),
nodeSize: PropTypes.arrayOf(PropTypes.number),
separation: PropTypes.func,
linkComponent: PropTypes.any,
nodeComponent: PropTypes.any
};
export default function Tree({
top,
left,
className,
root,
size,
nodeSize,
separation,
children,
linkComponent = DefaultLink,
nodeComponent = DefaultNode,
...restProps
}) {
这是正确的输入方式,我认为它应该是一个React.FunctionComponent,例如:
export interface TreeProps<Datum, LinkComponentType = any, NodeComponentType = any> {
root: HierarchyNode<Datum>;
top?: number;
left?: number;
className?: string;
size?: [number, number];
linkComponent: React.ComponentType<LinkComponentType>;
separation: (a: HierarchyPointNode<Datum>, b: HierarchyPointNode<Datum>) => number;
nodeComponent: React.ComponentType<NodeComponentType>;
nodeSize?: [number, number];
}
export declare function Tree<
Datum,
LinkComponentType = any,
NodeComponentType = any
>(args: TreeProps<Datum, LinkComponentType, NodeComponentType>): JSX.Element;
但是我将无法传递类型参数。
答案 0 :(得分:2)
您可以在/etc/hosts
中声明一个模块:
device administrator
.d.ts
正是您导入软件包或通过npm或yarn进行安装的名称。
这样,您将可以通过这种方式导入declare module 'NAME_OF_THE_PACKAGE' {
export interface TreeProps<Datum, LinkComponentType = any, NodeComponentType = any> {
root: HierarchyNode<Datum>;
top?: number;
left?: number;
className?: string;
size?: [number, number];
linkComponent: React.ComponentType<LinkComponentType>;
separation: (a: HierarchyPointNode<Datum>, b: HierarchyPointNode<Datum>) => number;
nodeComponent: React.ComponentType<NodeComponentType>;
nodeSize?: [number, number];
}
export function Tree<Datum, LinkComponentType = any, NodeComponentType = any>(
args: TreeProps<Datum, LinkComponentType, NodeComponentType>
): JSX.Element;
}
和NAME_OF_THE_PACKAGE
TreeProps
您可以阅读有关模块here的更多信息(请查看如何声明JavaScript库的示例-“使用其他JavaScript库”)。
答案 1 :(得分:0)
您可以声明这样的类型
export type Tree<D, LC = any, NC = any> =
React.FunctionComponent<TreeProps<D, LC, NC>> => JSX.Element
用法
const Tree: Tree<a,b,c> = (props) => <></>
答案 2 :(得分:0)
您可以
declare const Tree: React.FunctionComponent<TreeProps<Datum, LinkComponentType, NodeComponentType>>;
export default Tree;
Tree
将是React.FunctionComponent<P>
类型的(props: PropsWithChildren<P>, context?: any): ReactElement | null;
(功能组件)。
您可能对declare
关键字感到困惑。我发现最好的描述是here。
要使用语法创建类型为React.FunctionComponent<P>
的函数
const Tree: React.FunctionComponent<TreeProps<Datum, LinkComponentType, NodeComponentType>> =
(props) => {
return <div className={props.className}>
Some div
</div>
}
请注意,这里不需要declare
关键字。