6

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?

radix
  • 795
  • 1
  • 5
  • 16

3 Answers3

9

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.

  1. Add definitions to package.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

zlumer
  • 6,844
  • 1
  • 25
  • 25
  • thanks, but specifying the **decleration: true** flag creates a definition file for each file and not a single index.d.ts – radix Sep 14 '16 at 13:56
  • If you need to concatenate `.d.ts` files, you can use https://github.com/SitePen/dts-generator – zlumer Sep 14 '16 at 14:08
  • i looked at the project https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/material-ui Are the authors create the typings manually for each component? Or are they using a automatic tool for it? I want to expose a type definition for all my react typescript components i wrote. – radix Sep 17 '16 at 15:53
  • If you include your typings in the NPM module itself, everyone can use it automatically. DefinitelyTyped repository contains external typings for the JS modules that do not include them. – zlumer Sep 18 '16 at 00:10
  • Do i need to make a single d.ts file or just publishing multiple tsx files for example will suffice? – radix Sep 18 '16 at 06:28
  • As far as I remember, multiple `.tsx` files won't work, you have to provide a `.d.ts` file – zlumer Sep 18 '16 at 16:34
8

as mentioned Here: https://stackoverflow.com/a/65629179/10606346

The easiest way to have a .d.ts file out of the box with React is to put it in src folder and name it global.d.ts like:

src/global.d.ts

sina
  • 2,103
  • 1
  • 19
  • 26
2

Add this inside your tsconfig.json

{
  "compilerOptions": {
    "declaration": true,
    "declarationDir": "build" // the name of the build folder generated
    }
}
Harsh Boricha
  • 93
  • 1
  • 7
  • 1
    This helped alongside the response [here](https://stackoverflow.com/a/65629179/6793883) – Eunit May 01 '23 at 14:22