Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 307
radix Avatar asked Sep 14 '16 11:09

radix


People also ask

Is it possible to generate TypeScript declaration files from JS library?

With TypeScript 3.7, TypeScript added support for generating . d. ts files from JavaScript using JSDoc syntax. This set up means you can own the editor experience of TypeScript-powered editors without porting your project to TypeScript, or having to maintain .

How do I create a TypeScript component?

Using TypeScript, here's how we define the component: // Input. tsx import React from "react"; type Props = { onChange: (str: string) => void; placeholder: string; name: string; value?: string; }; function Input({ onChange, name, placeholder, value = "" }: Props) { return ( <input onChange={event => onChange(event.


1 Answers

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 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

like image 73
zlumer Avatar answered Sep 18 '22 11:09

zlumer