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:
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.
Within TypeScript, React.Component is a generic type (aka React.Component<PropType, StateType> ), so you want to provide it with (optional) prop and state type parameters: type MyProps = { // using `interface` is also ok message: string; }; type MyState = { count: number; // like this }; class App extends React.
A functional(a.k.a. stateless) component is just a plain javascript function which takes props as an argument and returns a react element. const MyStatelessComponent = props => React. createElement('div', null, props.name);
To use state in functional component use useState hook. This hook returns a tuple of two values. The first one is the current value of the state, the second one is a function to update the state. // into useState as an argument.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With