The TypeScript error TS2307 occurs when my module cannot be located in the index.d.ts file

I'm encountering an issue that is giving me trouble. I need to share some interfaces and types across my class files.

The structure of my repository looks like this:

test
  -> dist/
  -> src/
    -> index.ts
  -> .babelrc
  -> .eslintrc.js
  -> index.d.ts
  -> package.json
  -> tsconfig.json

In index.d.ts:

declare module test { // I've try with 'declare namespace test' but the result is the same
  export interface LabeledValue {
    label: string;
    size: number;
  }
}

When I try to import LabeledValue in index.ts, I receive an error that I can't comprehend:

import { LabeledValue} from 'test'; //  TS2307: Cannot find module 'test'.

src/index.ts

import {LabeledValue} from 'test';

function printLabel(labeledObj: LabeledValue) {
  console.log(labeledObj.label);
}

let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);

package.json:

{
  "name": "test",
  "types": "index.d.ts",
  "version": "1.0.0",
  "description": "test",
  "author": "oyabi",
  "license": "MIT",
  "private": true,
  "scripts": {
    "type-check": "tsc --noEmit",
    "type-check:watch": "yarn type-check --watch",
    "build": "npm run build:types && npm run build:js",
    "build:types": "tsc --emitDeclarationOnly",
    "build:js": "babel src --out-dir dist --extensions \".ts,.tsx\" --source-maps inline"
  },
  "dependencies": {
    "axios": "^0.19.0",
    ...
  },
  "devDependencies": {
    "@babel/cli": "^7.7.0",
    ...
  }
}

.babelrc

{
  "presets": ["@babel/typescript",
    ["airbnb", {
      "useBuiltIns": "usage"
    }]
  ],
  "plugins": [
    "syntax-class-properties",
    "transform-class-properties"
  ]
}

.eslintrc

module.exports = {
  root: true,
  parser: "@typescript-eslint/parser",
  ...
};

tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    ...
  },
  "include": ["index.d.ts"]
}

My actual code is more complex, but this should give you a good understanding of the issue. The error occurs in Visual Studio Code and with yarn build command. You can use yarn tsc src/index.ts to see the error.

If you have any suggestions on how to resolve this problem, please let me know.

Answer №1

By using the package eslint-import-resolver-typescript and its default settings, I was able to successfully resolve the installation issue I was facing.

Answer №2

Be sure to save your document with the .ts file extension

Answer №3

When using ES imports, ensure you import as shown below:

import {Item} from 'example';

This means you must have an ES module and not use namespace/module keywords, which are specific to TypeScript modules.

Solution

To resolve this, update your index.d.ts file to look like this:

  export interface Item {
    name: string;
    quantity: number;
  }

By including a top-level export, your file becomes an ES module and allows your ES import to function correctly.

Answer №4

Encountered a ts(2307) error in Visual Studio Code related to a module in my test file. The root cause was the use of a file named tsconfig.misc.json for compiling the test files, which worked fine for most VSCode tasks except for this particular issue. As soon as I renamed the file to tsconfig.json in the test subdirectory of my project, the problem was resolved.

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

Display an error popup if a server issue occurs

I'm considering implementing an Error modal to be displayed in case of a server error upon submitting a panel. I'm contemplating whether the appropriate approach would be within the catch statement? The basic code snippet I currently have is: u ...

Is there a way for me to navigate from one child view to another by clicking on [routerLink]?

Currently, I am facing an issue with switching views on my Angular website. The problem arises when I attempt to navigate from one child view to another within the application. Clicking on a button with the routerlink successfully takes me to the new view, ...

Ensure the variable is valid by using a type guard in the false branch

I am attempting to use a type guard to narrow down a complex type. In my scenario, I want the false branch of the type guard to recognize the complement of the narrowed type. interface Model { side: 'left' | 'right'; } interface LeftMo ...

The specified column `EventChart.åå` is not found within the existing database

I've been developing a dashboard application using Prisma, Next.js, and supabase. Recently, I encountered an issue when making a GET request. Prisma throws an error mentioning a column EventChart.åå, with a strange alphabet "åå" that I haven&apos ...

Unlocking the Power of FusionAuth in NativeScript: A Guide

While attempting to utilize a library based on nativescript documentation, I encountered an issue where certain modules like net and tls were not being automatically discovered. After using npm install to include tls and net, the problem persisted with t ...

I'm seeking a way to access the input element within the InputGroup component of BlueprintJs in my

The BluePrintJS React InputGroup component offers a convenient user interface for modern applications. However, it does not provide direct access to the internal <input> element. There are two primary reasons why I need to access the input element: ...

Show the current status of an API call in React using TypeScript

As a beginner in React and TypeScript, I'm working on calling a Graph API using POST method. Below is my code snippet: const OwnerPage: React.FunctionComponent = () => { const [TextFieldValue, setTextFieldValue] = React.useState('& ...

Restrict the parameter type using a type predicate

How can I effectively narrow types based on the value of a single field in TypeScript? It seems that using type predicates may not be working as expected to narrow down the types of other parameters within a type. Is there a way to ensure correct type na ...

Propagating numerical values through iterative iterations

I am currently facing an issue with passing values as props to a component using the forEach method in JavaScript. In addition to passing the existing values from an array, I also want to send another value that needs to be incremented by 1 for each iterat ...

Using ngIf for various types of keys within a JavaScript array

concerts: [ { key: "field_concerts_time", lbl: "Date" }, { key: ["field_concert_fromtime", "field_concert_totime"], lbl: "Time", concat: "to" }, { key: "field_concerts_agereq", lbl: "Age R ...

Angular 13's APP_INITIALIZER doesn't wait as expected

Recently, I have been in the process of upgrading from okta/okta-angular version 3.x to 5.x and encountered an unexpected bug. Upon startup of the application, we utilized APP_INITIALIZER to trigger appInitializerFactory(configService: ConfigService), whi ...

Dynamic getter/setter in Typescript allows for the creation of functions

I'm facing a challenge in making Typescript automatically infer types for dynamically created getter and setter functions. In my code, I have a class called MyClass which contains a map of containers: type Container = { get: () => Content s ...

Using TypeOrm QueryBuilder to establish multiple relations with a single table

Thank you for taking the time to read and offer your assistance! I am facing a specific issue with my "Offer" entity where it has multiple relations to "User". The code snippet below illustrates these relationships: @ManyToOne(() => User, (user) => ...

Is there a way for me to indicate to my custom component the specific location within an input message where a value should be displayed

I'm currently developing a value selector component in ionic/angular and I've encountered an issue with the message/title that I want to pass to the component. I want to be able to specify where the selected value should appear within the message ...

There seems to be an issue with accessing the 'request' property of an undefined object

Currently, I am in the process of incorporating a base service into an Angular application. This service is designed to provide methods to other services for composing requests with default headers and options. However, I encounter an issue when attempting ...

Switching a material-ui input control instead of a textfield for materials-ui-datepicker: the ultimate guide

Within my React application (v16.3), I am utilizing the DatePicker component from the material-ui-pickers library to render date-picker controls. This particular component renders a Material-UI TextField. However, I am interested in modifying it to only di ...

Error in Writing Functional Components with Typescript in React

I am struggling to create a versatile functional component and encountering issues like the one shown in this https://i.stack.imgur.com/WQkKg.png: Here is the code snippet: interface IAppTable<Type> { height: number; data: Type[]; tableLayout: ...

In TypeScript, this regular expression dialect does not permit the use of category shorthand

Recently, I attempted to implement a regular expression in TypeScript: I ran the following code: const pass = /^[\pL\pM\pN_-]+$/u.test(control.value) || !control.value; To my surprise, an error occurred: "Category shorthand not allowed in ...

Combining various DTOs in a seamless manner for validation in TypeScript is made easy with the class-validator fusion technique

As I delved into my NestJS project, I found the class-validation aspect to be quite bothersome. It felt like I was constantly repeating the same classes with identical decorators. For example: export class DTO1 { @IsDefined() @IsString() name: ...

Is there a way to incorporate a dropdown feature into a search bar using Ant Design?

I'm currently working on a project that requires me to incorporate two drop-down menus inside the search box. Despite following the guidelines provided in the documentation (https://ant.design/components/input), I encountered a problem when trying to ...