pen*_*lip 10 typescript reactjs type-definition
我正在尝试为现有的无状态 React组件套件创建类型定义,因此我可以自动生成文档并改善团队工具中的智能感知。
一个示例组件可能如下所示:
myComponent.js
import React from 'react';
export const MyComponent = ({ prop1, prop2, prop3 }) => (
<div>
{ prop1 ? prop2 : prop3 }
</div>
);
Run Code Online (Sandbox Code Playgroud)
我希望我的类型定义为:
看着这个创建的例子阵营使用打字稿成分,我发现了类型:React.SFC。
我试图在我的定义中使用它:
索引
declare module "MyComponent" {
import React from 'react';
interface MyComponentProps {
prop1: boolean;
prop2?: string;
prop3?: string;
}
export const MyComponent = React.SFC<MyComponentProps>
}
Run Code Online (Sandbox Code Playgroud)
但我收到棉绒错误 [ts] '(' expected.
我是TypeScript的新手,但是我显然缺少一些东西,但是找不到关于为无状态组件创建类型定义的文章。
编辑 要明确,我不想在TypeScript中重写我的组件。我想为现有的ES6无状态组件创建类型定义文件(* .d.ts)。
小智 11
尝试这个:
declare module "MyComponent" {
import React from 'react';
interface MyComponentProps {
prop1: boolean;
prop2?: string;
prop3?: string;
}
export const MyComponent: (props: MyComponentProps) => React.SFC<MyComponentProps>
}
Run Code Online (Sandbox Code Playgroud)
来自官方 React 页面推荐类型定义
经过大量摆弄后,我们决定进行以下设置。
import React from 'react';
export interface MyComponentProps {
prop1: boolean;
prop2?: string;
prop3?: string;
}
declare const MyComponent: React.SFC<MyComponentProps>
export default MyComponent
Run Code Online (Sandbox Code Playgroud)
灵感来自于:https : //github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/material-ui/index.d.ts
它可以与TypeDoc以及VS Code的智能感知一起很好地工作。
我相信这export default是在此处破解智能感知的关键。
| 归档时间: |
|
| 查看次数: |
8118 次 |
| 最近记录: |