How to make your own simple TypeScript typings for existing React component

If you are using React and TypeScript together as I do, you probably noticed that lot of third-party React components you find on Github don’t have type definition files and you don’t get benefit from all great things you from Typescript. If you still don’t know anything about TypeScript definitely check it out.

First thing it bothered me in my case (I am using Visual Studio) is that I can’t write ES6 import statements for those components that leave inside node_modules folder.

Notice how I am here importing custom component inside components folder. It works great. But when I try to import react-particles-js react component (from node_modules folder) I get this error in Visual Studio:

Cannot find module ‘react-particles-js’. To get around this I used to use require statement instead.

const Particles=require(‘react-particles-js’).

It worked great because Visual Studio was not complaining now about missing module.

Unfortunatelly, I don’t get any intellisense support (one benefit of TypeScript) when I try to use Particles component.

I decided to make my own type definition file for Particles component.

Fortunatelly it is not hard to start. I created folder typings under root (in fact I already had it because I had other d.ts files living in here like react.d.ts.

I created react-particles-js.d.ts file inside folder and created TypeScript module react-particles-js like this:

Notice how I am here using export default. I am exporting default to be able to use it like this:

import Particles from 'react-particles-js".

If I didn’t do that I would need to access Particles component like this:

import {Particles} from ''react-particles-js"

If you need to export other things except default thing you can just use export keyword (notice export interface ParticlesProps

and use it like this:

import Particles,{ParticlesProps} from 'react-particles-js'.

Because Particles compoent is React component it is of type React.ComponentClass where props is interface for props that this component will receive. (in this case width, height, params, style props.

Notice now how I am using this component:

I get intellisense support inside my TSX for that component and with F12 I can jump to file where definition lives.