radix radix - 2 months ago 8
React JSX Question

Generating/Maintaining a typescript definition file for my react typescript component library

I am building a react library in typescript and i want to provide consumers of this library a typescript definition file.

How do i make sure the typescript definition file is always correct an matching the js code?

Or if my components are written in typescript is there a way to generate a single d.ts file from all the generated d.ts files the compiler generated for me?

Answer

If you are the author of the library, it's extremely easy to provide and maintain the definitions. It works the same way regardless of the library you're using (such as React).

1. Create .d.ts file

You can create a .d.ts file by passing -d to compiler arguments or adding declaration: true in your tsconfig.json.

2. Add definitions to project.json

Add field named typings to your project.json, e.g. "typings": "./index.d.ts" (./index.d.ts is actually the default value if typings is omitted).


TypeScript compiler will automatically use provided typings if the user installs your library via NPM.

More info:
Writing Declaration Files
Typings for NPM packages

Comments