Search code examples
reactjstypescripttype-definition

How do I create a TypeScript type definition for a stateless React component?


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:

  • Define which props are allowed (and which are required)
  • That it will return JSX

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>
}

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

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.

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.


Solution

  • 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
    

    The inspiration for this was taken from: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/material-ui/index.d.ts

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

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