wmik
wmik

Reputation: 784

Adding typescript typings to react components written in javascript

I have a set of react components written in javascript and flow which I would like to add typings to support typescript. I'm not entirely sure how to approach this so any help would be appreciated. Here's my project structure:

/
|_src
  |_index.js
  |_components
    |_index.js
    |_ComponentName
      |_index.js
      |_ComponentName.js

Upvotes: 2

Views: 1590

Answers (2)

wmik
wmik

Reputation: 784

Update

I've tried these approaches so far:

// inside ComponentName folder
// index.d.ts
// import {ComponentName} from '/path/to/ComponentName/folder'

import * as React from 'react';

export = ComponentName
export as namespace ComponentName;

declare namespace ComponentName {
  interface ComponentProps { }
  const ComponentName: React.SFC<ComponentProps> // for stateless functional components
}

Alternative #2

// inside ComponentName folder
// index.d.ts
// import ComponentName from "ComponentName";
declare module "ComponentName" { // play around with this ex: `projectName/ComponentName`
  import * as React from 'react';
  interface ComponentProps { }
  const ComponentName: React.SFC<ComponentProps>; // stateless fn component
  export default ComponentName; // play with this to suit your export flavor ex: export {ComponentName}
}

Test it works by creating a .tsx file and importing the components. Needs more work for intellisense in editors but so far it shows missing props error.

Upvotes: 3

negool
negool

Reputation: 59

I haven’t done this myself before but I came across this site that might help you: https://blog.logrocket.com/how-why-a-guide-to-using-typescript-with-react-fffb76c61614

Upvotes: 0

Related Questions