Tips on adding an external type to a global .d.ts file

In my TypeScript project, I am utilizing Moment.js for dealing with datetime objects. As part of this, I wish to create an object type that includes a key holding a value of type Moment.

However, upon adding the following snippet to a global definition file named test.d.ts, none of the interfaces defined within that file can be located anywhere in the project.

import { Moment } from 'moment';

interface Test {
  date: Moment;
}

Whenever I attempt to utilize this interface in either a .ts or .tsx file, a TypeScript error is triggered:

[at-loader] ./src/<examplefilename>.tsx:91:26 
    TS2304: Cannot find name 'Test'. 

Despite no issues being flagged by VSCode's TypeScript error checking or TSLint, the problem persists.

What steps should I take to import a type from an external module for utilization in a global definition file?

Answer №1

Starting from TypeScript version 3.3 onwards (and possibly even earlier, around 2.4 when dynamic imports were introduced), there are improved approaches to resolving this issue. You can now utilize either of the following methods:

interface Example {
  date: import('moment').Moment;
}

or

type Moment = import('moment').Moment;
interface Example {
  date: Moment;
}

No requirement to export any interfaces in order to achieve this solution ;)

Answer №2

Check out this sample global.d.ts snippet from a typical Create React App setup:

declare type LinkProps = import("react-router-dom").LinkProps;

declare interface Example extends LinkProps {
  customProp: string;
}

Answer №3

Whenever a file contains a top-level import or export statement, it becomes classified as a module. In order to access any of its contents (such as types or interfaces), they must be explicitly exported in that file and imported into other files where they are needed.

// dataTypes.d.ts
import { Widget } from 'cool-library';

export declare interface IDataStructure {
  name: string;
  value: number;
  widget: Widget;
}

// app.js
import { IDataStructure } from 'dataTypes';

const sampleData: IDataStructure = {
  name: 'Sample',
  value: 42
};

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

Struggling to obtain the Variable

Trying to send a POST request to my ESP8266 HTTP Server, I need to transmit 4 variables: onhour, offhour, onminute, offminute. These variables should be retrieved from a timepicker-component imported from "ng-bootstrap" Despite numerous attempts over the ...

Verify the type without making any assumptions about the checked type

Take a look at this type definition: interface ISmth<T> { id: number; data: T; } Now, I am interested in creating an array that contains elements of this type: var a = [{ id: 1, data: [], }, { id: 2, data: 4, }, { id: 3, data: "abc ...

Enumerate the names of the private properties within the class

I am working on a problem where I need to use some of the class properties as values in a map within the class. In the example below, I have used an array instead of a map because when a property is marked private, it is not included in the keyof list. How ...

Is there a way to turn off tsc pretty printing using the configuration file?

My typescript program is intentionally broken but I want to fix it. 12:17:23:~/hello $ cat hello.ts console.log("Hello World" 12:17:29:~/hello $ cat package.json { "dependencies": { "typescript": "^5.2.2" ...

Encountering an error in Angular 2: "date.getMonth is not a function

I am currently utilizing the Angular-2-datepicker in my project. Everything seems to be functioning properly, but whenever I attempt to set the [(date)] attribute, an error is thrown. An error stating that date.getMonth is not a function keeps popping u ...

Troubleshooting the Issue with Angular Material Dialog Imports

Hey there, I'm trying to utilize the Angular Material dialog, but I'm encountering issues with the imports and I can't seem to figure out what's wrong. I have an Angular Material module where I imported MatDialog, and I made sure to i ...

Issue in React Native and Firestore: The 'auth' property is not recognized in the specified type or an error object of unknown type

I am currently using Typescript in conjunction with Firebase and React Native. While working on the signup screen, I included Firebase like so: import * as firebase from 'firebase/app'; import 'firebase/auth'; In my onSignUp function, ...

The role of providers in Angular applications

After creating a component and service in my project, I followed the documentation's instruction to include the service in the providers metadata of the component for injection. However, I found that it still works fine even without mentioning it in t ...

Is it achievable to display keys from an interface using Typescript in node.js?

Using node.js with typescript, I have a query. I defined a type from interfaces key, and I'm wondering if it's feasible to display the key list? interface IFooReal { prop1: string; prop2: number; } type KnownKeys<T> = { [K in ...

What are some strategies for circumventing the need for two switches?

My LayerEditor class consists of two private methods: export class LayerEditor { public layerManager: LayerManager; constructor() { this.layerManager = new LayerManager(this); } private executeCommand() { ...

One-of-a-kind npm module for typescript

As part of my project, I am enhancing an existing library to make it compatible with TypeScript. To showcase this modification, I have condensed it into a succinct Minimal working example The specified requirements To ensure backward compatibility, the li ...

Sending user input data from a React text field to a function as arguments

Below are input fields, from which I need to retrieve the entered values and pass them to the onClick event of the button displayed below. <input type="text" style={textFieldStyle} name="topicBox" placeholder="Enter topic here..."/> <input type=" ...

Angular project icons not displaying in the browser

My current project in Angular was functioning properly until recently. I am facing an issue where the images are not being displayed on the browser when I run ng serve, resulting in a 404 error. Interestingly, everything else seems to be working fine witho ...

Discover the data type of the subfield within an interface or type in Typescript

Check out the interface and type declarations provided below: interface Foo { bar: { a: number b: string } } type Foo = { bar: { a: number b: string } } Is it possible to obtain the type definitions for "baz"? This will allow us ...

Creating a new list by grouping elements from an existing list

I have successfully received data from my API in the following format: [ {grade: "Grade A", id: 1, ifsGrade: "A1XX", ifsType: "01XX", points: 22, type: "Type_1"}, {grade: "Grade B", id: 2, ifsGrade: &quo ...

Upon upgrading @types/angular, I encountered error TS2694 stating that the namespace 'angular' does not have an exported member 'xxx'

Following the upgrade of angular and @types/angular to version 1.6.x, an array of TS2694 errors suddenly appeared: error TS2694: Namespace 'angular' does not include an exported member named 'material' error TS2694: Namespace 'ang ...

What's the most effective method for transferring data to different components?

How can I efficiently pass a user info object to all low-level components, even if they are grandchildren? Would using @input work or is there another method to achieve this? Here is the code for my root component: constructor(private _state: GlobalSta ...

Utilizing Gulp to Convert TypeScript Exports into a JSON File

I have a set of TypeScript files, some of which export a specific variable - named APIS - which contains an array of objects. My goal is to extract the values from all of these exports and save them into a JSON file using Gulp. Let's consider a direc ...

Can one utilize generic parameter value within a conditional type result field in Typescript?

Trying to create a versatile function type for data transformation can be a bit tricky. When dealing with a single object, it's straightforward: export type SingleObjFunction<InputDataType, OutputDataType> = (object: InputDataType) => Outpu ...

Issue: Formcontrolname attribute is undefined causing TypeError when trying to retrieve 'get' property.Remember to define formcontrolname attribute to

Having trouble creating a form at the moment and keep encountering this error: 'ERROR TypeError: Cannot read property 'get' of undefined' Even after trying various solutions like using formControlName in brackets or accessing the va ...