如何为无状态React组件创建TypeScript类型定义? [英] How do I create a TypeScript type definition for a stateless React component?

查看:546
本文介绍了如何为无状态React组件创建TypeScript类型定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为现有的无状态 React组件套件创建类型定义,因此我可以自动生成文档并改善团队工具中的智能感知.

I'm trying create type definitions for an existing suite of stateless React components, so I can generate documentation automagically and to improve intellisense in my team's tooling.

示例组件可能如下所示:

An example component could look like this:

myComponent.js

import React from 'react';

export const MyComponent = ({ prop1, prop2, prop3 }) => (
    <div>
        { prop1 ? prop2 : prop3 }
    </div>
);

我希望我的类型定义为:

I would like my type definition to:

  • 定义允许哪些道具(哪些是必需的)
  • 它将返回JSX

查看创建的示例使用TypeScript的组件,我发现了类型:React.SFC.

Looking at this example of creating React components using TypeScript, I discovered the type: React.SFC.

我试图在我的定义中使用它:

I tried to use this in my definition:

index.d.ts

declare module "MyComponent" {
    import React from 'react';

    interface MyComponentProps {
        prop1: boolean;
        prop2?: string;
        prop3?: string;
    }

    export const MyComponent = React.SFC<MyComponentProps>
}

但是我收到了掉毛错误[ts] '(' expected.

But I'm getting the linting error [ts] '(' expected.

我对TypeScript还是很陌生,显然我缺少一些东西,但是找不到关于为无状态组件创建类型定义的文章.

I'm pretty new to TypeScript and I am clearly missing something, but I can't find any articles on creating type definitions for stateless components.

编辑 需要明确的是,我不想用TypeScript重写我的组件.我想为现有的ES6无状态组件创建类型定义文件(* .d.ts).

EDIT To be clear, I don't want to rewrite my components in TypeScript. I want to create a type definition file (*.d.ts) for an existing ES6 stateless component.

推荐答案

经过很多摆弄后,我们决定进行以下设置.

After a lot of fiddling, we have settled on the following set up.

import React from 'react';

export interface MyComponentProps {
    prop1: boolean;
    prop2?: string;
    prop3?: string;
}

declare const MyComponent: React.SFC<MyComponentProps>

export default MyComponent

其灵感来自于: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/material-ui/index.d.ts

它与TypeDoc以及VS Code的智能感知一起很好地工作.

It works well with TypeDoc and also VS Code's intellisense.

我相信export default是破解此处的智能感知的关键.

I believe export default was the key to cracking intellisense here.

这篇关于如何为无状态React组件创建TypeScript类型定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆