2

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
3
  • Do you want to auto-generate the .d.ts from your .ts files or maintain your own .d.ts files? Commented Apr 18, 2018 at 15:31
  • I don't have any .ts files yet, so I think maybe maintain my own for now. Commented Apr 19, 2018 at 11:50
  • I suggest reading the official docs and also looking at DefinitelyTyped for real-life implementations. For example, tape is short and sweet. Commented Apr 19, 2018 at 16:29

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Thanks for the reply. Although I don't really want to have to rewrite to typescript. I was thinking more like bundling *.d.ts files with the library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.