What is the process for publishing TypeScript interface definitions via npm?

I've been grappling with this problem for the past few days, scouring the internet and reading extensively, but I haven't come across any examples that match my specific scenario. My goal is to publish a library using npm that includes its own type definitions.

I recently delved into TypeScript because other teams require my library to support typings.

Here's an overview of what I have so far:

tsconfig.json:

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "allowUmdGlobalAccess": true,
    "baseUrl": ".",
    "declaration": true,
    "declarationMap": true,
    "forceConsistentCasingInFileNames": true,
    "jsx": "react",
    "module": "commonjs",
    "noImplicitAny": true,
    "noUnusedParameters": true,
    "noUnusedLocals": true,
    "outDir": "./dist/",
    "paths": {
    },
    "sourceMap": true,
    "strict": true,
    "target": "es6",
  },
  "include": [
    "./src"
  ]
}

package.json:

  "main": "dist/index.js",
  "scripts": {
    "tsc": "tsc",
    "prepack": "npm run clean && npm run tsc",
  },
  "types": "./dist/index.d.ts",

src/index.ts (built into dist/index.js + dist/index.d.ts):

export { IAction, IState } from './types';

src/types (built into dist/types.js + dist/types.d.ts):

import { Map } from 'immutable';

export interface IAction {
  type: string;
  payload: object;
}

export interface IState extends Map<string, Map<string, any>> {
}

I have additional code in this repository that successfully uses these interfaces. The TypeScript compiler doesn't raise any issues during the build process.

Currently, I package the library by running npm pack and then install it in another project using

npm install ../path/to/my/file-0.0.1.tgz
. When attempting to use my interfaces (such as in a Redux reducer), like so:

import { IAction, IState } from 'my-lib';  // <-- matching package name specified in package.json

const reducer = (state: IState, action: IAction) => {
  ...
}

However, I'm encountering the following errors:

error TS2709: Cannot use namespace 'IState' as a type.
error TS2709: Cannot use namespace 'IAction' as a type.

I'm struggling to understand why this error occurs. Is there an additional step I need to take to generate my definition file automatically? Ideally, I'd prefer not to create it manually.

If you require further details, please let me know.

Thank you for your assistance and patience in reviewing this information.

Answer №1

Make sure to add the following code snippet to your package.json file:


  ...
  "main": "dist/index.js",
  "typings": "dist/index.d.ts",
  "source": "lib/index.ts",
  "files": [
    "dist",
    "lib"
  ],
  ...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered a runtime error in NgRx 7.4.0: "Uncaught TypeError: ctor is not a

I'm facing difficulties trying to figure out why I can't register my effects with NgRx version 7.4.0. Despite simplifying my effects class in search of a solution, I keep encountering the following error: main.79a79285b0ad5f8b4e8a.js:33529 Uncau ...

Having trouble importing the d3-geo package into a Node.js TypeScript project

Seeking a way to test the inclusion of specific latitude and longitude coordinates within different GeoJSON Features using code. When attempting this with: import d3 from 'd3-geo'; // or: import * as d3 from 'd3-geo' // no difference ...

Utilizing Typescript Generics in Arrow Function to Combine Two Arguments

For instance, I am working with this code in a .tsx file extension const Add = <T,>(arg0: T, arg1: T): T => arg0 + arg1; const A = Add(1, 2); const B = Add('1', '2') However, I am encountering an issue, as there is an error m ...

Looking to conceal the input div without compromising the functionality in Angular 14

Here is the provided HTML code for scanning a barcoder and assigning it to the barCodeNumber variable. The onChange() function will be called once the barcode is scanned. Question: How can I hide the div on the UI while still allowing the function to work ...

Oh no! A critical mistake has occurred: Mark-compact operations are not working efficiently near the heap limit, leading to a failed allocation due to the

My project is not particularly complex, I only just started it. However, when I run the command npm run dev, node js consumes more than 4GB of memory and eventually crashes with a fatal error: --- Last few GCs --- [16804:0000018EB02350F0] 128835 ms: Mar ...

The dynamic fusion of Typescript and Angular 2 creates a powerful

private nodes = []; constructor(private nodeService: NodeService) {} this.nodeService.fetchNodes('APIEndpoint') .subscribe((data) => { this.nodes.push(data); }); console.log(this.nodes) This ...

What are the steps to set up tsline in settings.json file?

Currently utilizing visual studio code Upon searching for the settings.json file, the contents appear as follows: { "liveServer.settings.donotVerifyTags": true, "liveServer.settings.donotShowInfoMsg": true, "javascript ...

What is the mechanism behind making a Promise appear synchronous when using a Proxy in JavaScript?

const handler: ProxyHandler<any> = { get: (target: Promise<any>, prop: string, receiver: any) => { return target.then((o) => { return o[prop].apply(o); }); }, }; return new Proxy(obj, handler) ...

Using Angular 2: Applying a specific class to a single element with [ngClass]

I have a header table with arrows indicating sorting order, using Bootstrap icons. However, when I click on a column, all columns receive the icon class. Here is an example of what I mean: https://i.sstatic.net/CAS81.png Below is the code snippet: HTML ...

Generate dynamic property values based on calculations

I am facing a challenge with a form that I have designed. Could you guide me on how to dynamically update the value of the calculate field (contingency) whenever the user modifies the values of budget1 and budget2? I have attempted several approaches witho ...

Replicating entities in TypeScript

I am currently developing an Angular 2 application using TypeScript. In a User Management component, I have implemented a table that displays all the users in my system. When a user is clicked on within the table, a form appears with their complete set of ...

Encountering a TypeScript error while trying to pass the myDecorator function as a decorate prop to React

Encountering a TS error that states: (property) decorate?: ((entry: NodeEntry<Node>) => BaseRange[]) | undefined Type '([node, path]: [node: any, path: any]) => { anchor: { path: any; offset: string | number; }; focus: { path: any; offset: ...

How to initiate a refresh in a React.js component?

I created a basic todo app using React, TypeScript, and Node. Below is the main component: import * as React from "react" import {forwardRef, useCallback, useEffect} from "react" import {ITodo} from "../types/type.todo" import ...

What are the benefits of using one state in React with useState compared to having multiple states?

Is it more beneficial to optimize and enhance code readability in React using Hooks and Functional components by utilizing a single setState hook or having multiple hooks per component? To further elaborate, let's consider the following: When workin ...

Receiving data from a service in Angular 2 with rxjs subscribe throws an error: it is not a

I've recently started working with Angular and I'm encountering an issue when trying to pass the _newArray to my child component using a shared service. Service fetchData(): Observable < any > { return forkJoin(this.fetchQuestions(), th ...

Examining the asynchronous function to cause an error using mocha

I am facing a challenge with testing an async function that is supposed to run for 2000ms before throwing an exception. Despite my efforts using Mocha / chai, the test does not seem to be working as expected. Here's what I have attempted: First appr ...

What steps should I take to resolve the issue I am encountering while attempting to install packages using npm

npm ERR! Linux 4.15.0-36-generic npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "-g" "create-react-app" npm ERR! node v8.10.0 npm ERR! npm v3.5.2 npm ERR! path /tmp/npm-7054-19e3727d npm ERR! code EROFS npm ERR! errno -30 npm ERR! syscall mkdir n ...

Locate the specific version of a JavaScript library within compiled JS files

The dist folder houses the results of running npm install. If I don't have access to the original package.json file used during the compilation of the distributable, how can I determine the version of a particular library that was utilized in the ins ...

API endpoint generating a Vue component as a rendered output

In the process of developing a document templater service, I am faced with the challenge of handling numerous document templates (contracts, protocols, etc.) written in Vue. The concept revolves around clients sending props in the body, which are then pass ...

Issue with npm symlink while rebuilding for homestead

I am encountering issues while attempting to utilize npm for a project I am currently working on. Every time I execute npm run dev vagrant@homestead:~/code/testlaravel$ npm run dev > @ dev /home/vagrant/code/testlaravel > npm run development > ...