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?

3 Answers 3

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

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

6 Comments

thanks, but specifying the decleration: true flag creates a definition file for each file and not a single index.d.ts
If you need to concatenate .d.ts files, you can use github.com/SitePen/dts-generator
i looked at the project github.com/DefinitelyTyped/DefinitelyTyped/tree/master/… 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.
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.
Do i need to make a single d.ts file or just publishing multiple tsx files for example will suffice?
|
9

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

Comments

3

Add this inside your tsconfig.json

{
  "compilerOptions": {
    "declaration": true,
    "declarationDir": "build" // the name of the build folder generated
    }
}

1 Comment

This helped alongside the response here

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.