What is the best way to import a data type from another file into a `.d.ts` file without converting it into a module?

Recently encountered a peculiar scenario involving d.ts files and namespaces.

I have some d.ts files where I define and merge a namespace called PROJECT.

Take a look at how it's declared and automatically merged (across multiple files) below:

file1.d.ts ----- file2.d.ts ----- file3.d.ts

declare namespace PROJECT {

  interface SOME_INTERFACE {
    ...
  }

  type SOME_TYPE = SOME_UNION_TYPE

  // ETC
}

This PROJECT namespace is accessible from all files within my project. For example:

SomeComponent.tsx

const someVariable: PROJECT.SOME_INTERFACE = { 
  // ... 
};

This behavior is entirely as expected.

The issue arose when I attempted to declare another namespace.

ADMIN_BLOGPOST.d.ts

import type { ACTION_THUNK_GENERIC } from "@hooks/useReducerThunk";

declare namespace ADMIN_BLOGPOST {
  // HERE I DECLARE MULTIPLE TYPES
  // AND ONE OF THE TYPES USES THE `ACTION_THUNK_GENERIC` TYPE, WHICH IS BEING IMPORTED HERE

  type ACTION_THUNK = ACTION_THUNK_GENERIC<ACTION,GET_STATE>
}

Solely because of the top-level import type statement for ACTION_THUNK_GENERIC, my namespace is no longer automatically available.

VSCode now considers ADMIN_BLOGPOST.d.ts as a module, requiring me to explicitly import the namespace before using it, like so:

SomeComponent.tsx

import type { ADMIN_BLOGPOST } from "@src/types/ADMIN_BLOGPOST";

const someVariable: ADMIN_BLOGPOST.ACTION_THUNK

If I remove the top-level import of ACTION_THUNK_GENERIC from the ADMIN_BLOGPOST.d.ts file, then the ADMIN_BLOGPOST namespace becomes available without prior importation.

However, that import is essential to me as I require the ACTION_THUNK_GENERIC type to construct the non-generic ACTION_THUNK type.

Is there an alternative approach to achieve this, ensuring that my ADMIN_BLOGPOST namespace is accessible without the need for preemptive importing? In other words, how can I perform an import inside a d.ts file without converting it into a module?

Answer №1

To easily work in a global namespace regardless of module imports, you can utilize the declare global statement. Here's an example:

import type { ACTION_THUNK_GENERIC } from "@hooks/useReducerThunk";
declare global {
  declare namespace ADMIN_BLOGPOST {
    type ACTION_THUNK = ACTION_THUNK_GENERIC<ACTION,GET_STATE>
  }
}

Another option is to use dynamic import like this:

declare namespace ADMIN_BLOGPOST {
  type ACTION_THUNK = import("@hooks/useReducerThunk").ACTION_THUNK_GENERIC<ACTION,GET_STATE>
}

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

Access a .docx file on my device by utilizing the Microsoft JavaScript API

In my current project, I am developing a Microsoft Word add-in using TypeScript, React, and the Word API. One of the key features of this add-in will allow users to open a document located on their computer, such as "C:\Test\Test.docx", with just ...

When using Angular with mdbootstrap, the mdb-tabs directive will move to the end if the ngIf condition is true

Currently facing a challenge with a significant amount of code here. It is referenced as follows: "ng-uikit-pro-standard": "file:ng-uikit-pro-standard-8.3.0.tgz", I am attempting to display a tab between 1 and 3 if a certain condition ...

Implementing experimental decorators and type reconciliation in TypeScript - A step-by-step guide

My basic component includes the following code snippet: import * as React from 'react'; import { withRouter, RouteComponentProps } from 'react-router-dom'; export interface Props { }; @withRouter export default class Movies extends R ...

Preventing the compilation process from overwriting process.env variables in webpack: A step-by-step guide

Scenario I am currently working on developing AWS Lambda functions and compiling the code using webpack. After reading various articles, I have come to know that the process.env variables get automatically replaced during compilation. While this feature ...

Are React component properties enclosed in curly braces?

I have a new component configured like this: type customType = differentType<uniqueType1, uniqueType2, uniqueType3>; function customComponent({q}: customType) When called, it looks like this: <customComponent {...myCustomVar} />, where myCus ...

How can I retrieve the row index in an Angular Mat-Table that has expandable content?

Having a mat-table with expandable content on a page, I am seeking a solution to record the row number of the table when clicked. While I successfully achieved this with a regular table in the HTML file using: <tr mat-row *matRowDef="let row; columns: ...

Interface with several generic types

In an attempt to create a parser that can parse data fields and convert them into a complete form for display purposes, the fields property plays a crucial role. This property will define each field in a JSON data array that the client receives from the ur ...

I'm curious, which redux architecture would you recommend for this specific scenario?

I'm currently developing an application and I'm facing a challenge in implementing Redux effectively in this particular scenario. Unfortunately, due to restrictions at my workplace, normalizing data is not an option. Let's consider the foll ...

Implement tooltip functionality in ssr chart using echarts

A chart is generated using echarts on the server-side: getChart.ts const chart = echarts.init(null, null, { renderer: 'svg', ssr: true, width: 400, height: 300 }); chart.setOption({ xAxis: { data: timeData }, ...

TypeScript throws an error if trying to access an Object variable using a String

While the code below is functioning as intended, I am encountering an error in the VS Code Typescript compiler stating that "Type 'String' cannot be used as an index type". Oddly enough, using a string literal instead of a variable like ...

Is subtyping causing issues in TypeScript's inheritance model?

I am currently utilizing TypeScript for my coding projects, and I have observed that it can allow the production of non-type-safe code. Despite implementing all the "strict" options available to me, the behavior I am experiencing goes against the principle ...

Iterating through typescript enums in Vue using v-for

Why is the v-for loop over an enum displaying both names and values? Is there a way to iterate only over the keys? export enum Colors { "RED" = 1, "BLUE" = 2, "GREEN" = 3, } <template> <div> <v ...

Exporting modules in TypeScript using "module.exports"

While working on my Yeoman generator, I initially wrote it in JavaScript like this: "use strict"; var Generator = require("yeoman-generator"); var chalk = rquire("chalk"); module.exports = class extends Generator { initializing() { this.log( c ...

The TypeScript function was anticipating one argument, however it received two instead

Can you help me fix the issue with my createUser() function? Why am I unable to pass parameters in Smoke.ts? Login.ts : interface User { url: string, email: string, } class Test{ async createUser(user: User) { await Page.setUrl(user.url); aw ...

Attribute specified does not belong to type 'DetailedHTMLProps<ButtonHTMLAttributes

I am working on creating a reusable 'button' component and I would like to include a href attribute so that when the button is clicked, it navigates to another page. An Issue Occurred: The following error was encountered: 'The type '{ ...

Angular can display text on hover based on the state shown in a <td> element

Working on an Angular 7 project, I have a <td> element where I display different colors to indicate the status of a task: Red - Indicates 'Delayed' Orange - Indicates 'In progress' Grey - Indicates 'Rejected' Cu ...

What is the best way to retrieve distinct objects based on LocId across all locations?

Encountering an issue while working on Angular 7: unable to return distinct or unique objects based on LocId. The goal is to retrieve unique objects from an array of objects containing all Locations. allLocations:any[]=[]; ngOnInit() { this.locationsServ ...

Issues with tracking changes in Vue.js when using reactive variables

After triggering a click event, I am attempting to choose a message from a json file. However, I am encountering an issue where the first click does not seem to select anything. Upon the second click, the selected messages are duplicated, and this pattern ...

Please place the accurate image inside the designated box based on the corresponding ID number

I am currently working on a function that retrieves image data from a database and displays it in HTML using *ngFor directive. In order to display the correct image, I need to fetch the ID associated with the image data and use it to retrieve the correspo ...

Using Angular 6 HttpClient to retrieve an object of a specific class

Previously, we were able to validate objects returned from http api calls using the instanceof keyword in Angular. However, with the introduction of the new HttpClient Module, this method no longer works. I have tried various simple methods, but the type c ...