What steps do I need to take to export my TypeScript declarations to an NPM package?

I have multiple repositories that share similar functionality. I want to export type declarations to an NPM package so I can easily install and use them in my projects.

Within the root directory, there is a folder called /declarations, containing several *.d.ts files with code snippets I want to expose. For example:

// declarations/maps.d.ts

declare interface LatLng {
  lat: number;
  lng: number;
}

declare interface MapMarker {
  id: string;
  position: LatLng;
}

I've searched online for information on this process, but there isn't much available and what I found varies greatly. This has raised some questions for me:

  1. To use these declarations in another project, should I export files with a *.d.ts extension or convert them to *.ts?
  2. If I need to export all files from the declarations folder, do I create an index.d.ts (or possibly index.ts) file?
  3. Do I have to compile the source code into plain JavaScript files using commands like npm run build or rollup before importing it into another project, or can I directly import the source code?
  4. When attempting to export declaration files like maps.d.ts, TypeScript gives an error saying "maps.d.ts is not a module." Does this mean I need to wrap the files in something like:
    declare module 'mapsModule' { export interface (...) }
  5. If not, is a regular
    export interface MapMaker { id: string }
    sufficient?
  6. I know I need to specify the types by adding a "types" property in package.json. Do I also need to indicate the main declaration file within package.json as well, such as:
  7. Should I include another index.ts (or index.d.ts) file in the root directory where I import from /declarations/index.d.ts?

Once I understand this process and have working types, my goal is to publish everything to an NPM package for easy installation everywhere. However, that's a step for later. I realize my questions may not be perfectly articulated and I might confuse terms and functionalities, as I'm still learning about TypeScript. Any guidance or resources you can recommend would be greatly appreciated. Thank you in advance for your help.

Answer №1

After reading a post on How to set up custom global interfaces (.d.ts files) for TypeScript?, including a popular answer by Daniel Tabuenca linked here, I came across some valuable insights:

The concept of "magically available interfaces" or global types is advised against and should mostly be avoided, especially when it comes to modern coding practices. It is recommended not to rely on ambient declaration files (e.g. d.ts files) for your own code. Instead, use plain .ts files to define your interfaces and types.

While this information didn't completely resolve my issue, it did provide me with a helpful indication of what might be causing it.

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

What could be the reason for encountering a Typescript ts(2345) error while trying to pass a mocked constant to .mockResolvedValue()?

Within my test.tsx file, I have the following code snippet: test('Photos will load', async () => { const mockCuratedPhotos = jest.spyOn(endpoints, 'getCuratedPhotos'); mockCuratedPhotos.mockResolvedValue(mockPhotos); awa ...

Angular2- Retrieving configuration information during application launch

Implementing a method to load configuration data from an ASP.NET web API using HTTP at startup via APP_INITIALIZER. This approach was influenced by a discussion on Stack Overflow about loading configuration in Angular2 here and here. Snippet from app.modu ...

Error Message: Unable to access 'map' property of undefined in TSX file

Component for displaying attendees in an activity interface IProps { attendees: IAttendee[] } export const ActivityListItemAttendees: React.FC<IProps> = ({attendees}) => { return ( <List horizontal> {attendees.ma ...

Why is Mongoose returning null when using findOne?

Here is a sample request: interface IGetFullnameRequest extends IAuthenticatedRequest { readonly body: Readonly<{ fullname: string; }>; } This is the controller function to get the fullname: const getFullname = async (req: IGetFullna ...

Sending a message through Discord.JS to a designated channel

Recently diving into Discord.JS, I am struggling to understand how to make my bot send a message to the General Chat when a new user joins. Many examples I've come across suggest using the following code: const channel = client.channels.cache.find(ch ...

Is it possible to customize a VSCode extension to function exclusively with certain programming languages?

Lately, I added a new extension to my VSCode setup that has proven to be quite beneficial for my workflow. If you're interested, you can find this helpful extension at This Repository. It allows you to easily highlight the starting and ending syntax ...

Creating a unique Elastic IP address for a single EC2 instance with the AWS CDK

I'm having an issue with my AWS CDK Stack where multiple Elastic IPs are being created for each public subnet in my VPC instead of just one. I only want one Elastic IP to be associated with a single EC2 instance. My simplified code snippet is as foll ...

Encountering a problem when launching the "vite-express" template on the Remix app (TSConfckParseError: error resolving "extends")

I recently launched a brand-new [email protected] project using the remix-run/remix/templates/vite-express template after executing this command: npx create-remix@latest --template remix-run/remix/templates/vite-express However, upon trying to run th ...

The member 'email' is not found in the promise type 'KindeUser | null'

I'm currently developing a chat feature that includes PDF document integration, using '@kinde-oss/kinde-auth-nextjs/server' for authentication. When trying to retrieve the 'email' property from the user object obtained through &apo ...

Is there a function return type that corresponds to the parameter types when the spread operator is used?

Is it possible to specify a return type for the Mixin() function below that would result in an intersection type based on the parameter types? function Mixin(...classRefs: any[]) { return merge(class {}, ...classRefs); } function merge(derived: any, ... ...

What is the best way to transform a JS const into TSX within a Next.js application?

Exploring the code in a captivating project on GitHub has been quite an adventure. The project, located at https://github.com/MaximeHeckel/linear-vaporwave-react-three-fiber, showcases a 3D next.js application that enables 3D rendering and animation of mes ...

Incorporate a generic type into a React Functional Component

I have developed the following component: import { FC } from "react"; export interface Option<T> { value: T; label: string; } interface TestComponentProps { name: string; options: Option<string>[]; value: string; onChang ...

Where can I find the @types for a specific lodash package?

Seeking to utilize a specific function from lodash - assignin. I have successfully installed lodash.assignin and incorporated it into my project: import assignIn = require('lodash.assignin'); However, when compiling, an error occurs: "error TS2 ...

Tips on excluding node_modules from typescript in Next.js 13

I am constructing a website in the next 13 versions with TypeScript, using the src folder and app directory. When I execute `npm run dev`, everything functions correctly. However, upon building, I encounter this error... ./node_modules/next-auth/src/core/l ...

Binding iframes in Angular 6

Is there a way to display iframe code stored in a variable within a div? Here's the HTML code: <div class="top-image" [innerHTML]="yt"></div> And here's the TypeScript code: yt = '<iframe class="w-100" src="https://www.you ...

Can you explain the purpose of this TypeScript code snippet? It declares a variable testOptions that can only be assigned one of the values "Undecided," "Yes," or "No," with a default value of "Undecided."

const testOptions: "Undecided" | "Yes" | "No" = "Undecided"; Can you explain the significance of this code snippet in typescript? How would you classify the variable testOptions? Is testOptions considered an array, string, or another d ...

Utilizing TypeScript Generics to Dynamically Set Tag Names in React

I am working on a straightforward polymorphic React component that is designed to render only tag names (such as span) and not custom React components (like MyComponent). I believe this can be achieved using JSX.IntrinsicElements. Here is the code snippet ...

In TypeScript, there is a mismatch between the function return type

I am new to TypeScript and trying to follow its recommendations, but I am having trouble understanding this particular issue. https://i.stack.imgur.com/fYQmQ.png After reading the definition of type EffectCallback, which is a function returning void, I t ...

Is there a way to prevent the leaderboard from resetting each time I restart my client?

Is it possible to prevent the leaderboard from resetting every time I restart my client? You can see an example here: https://i.stack.imgur.com/2nEPw.png Please disregard the "undefined" error, I will correct it. In the current setup, the leaderboard onl ...