Adding Typescript Support to React ES6 Components

Kasun Dilunika
Frontend Weekly
Published in
2 min readApr 12, 2017

Currently I am working on a project which requires some Sharepoint Webpart developments. Microsoft released a new framework called Sharepoint Framework to develop Sharepoint Webparts using client side technologies and O365 REST APIs. This new framework gives you three options to start your developments:

  1. Using plain Typescript
  2. Using React framework + Typescript
  3. Using Knockout

Since we already have some developed React Components we directly went with second option. We tried to reuse some of the react components inside our webparts. Then we hit the wall - Typescript !!!

Sections below describes this problem in details and how we jumped the wall Typescript by adding some typings support to our existing react components instead re writing them.

I am using react-npm-boilerplate sample project to explain this simple development. This project contains two simple React components inside components folder as follows: (initially index.d.ts was not there :) )

Directory Structure

If you directly use these components as a NPM package in your Sharepoint Webpart project, you will see some typescript compiler errors because typescript compiler is unable to find any of the Components in existing type definitions. Since this NPM package is something that you have full control, we can easily fix this typings issue by doing following steps:

  1. First, add a type definition file to describe the typings of the components
  2. Then re-publish the package to NPM registry. (npm run npmify)
  3. Finally, refer the new version of the package in the webpart project

Add index.d.ts file at the same place where index.js stays.

Now you will be able to get rid of typescript compiler issues and you will have intelisense as well. See … very simple !!!

Full source code for this project can be found in https://github.com/dtl-open/react-npm-boilerplate

References

  1. Guide to write Typescript definition files. https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html
  2. How to create your own type definition files http://blog.wolksoftware.com/contributing-to-definitelytyped

--

--