The tsconfig.json file does not support the path specified as "@types"

Having set up multiple absolute paths for my Next.js application, I encounter an issue where importing a component from the absolute path results in something like "../componentName" instead of "@components/componentName" when I am inside another folder. This inconsistency often requires manual adjustment in vsCode.

Another challenge I face is with a folder containing all my TypeScript types named /types. Despite creating a path to it, I continue to receive an error stating that it is not declared.

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "baseUrl": "./",
    "paths": {
      "@images/*": ["images/*"],
      "@lib/*": ["lib/*"],
      "@components/*": ["components/*"],
      "@types/*": ["types/*"],
      "@styles/*": ["styles/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}

/types/index.ts

export type { SocialFields } from "./objects/social-fields";
export type { HeroProps } from "./hero";
export type { ImageProps } from "./image";
export type { PostProps } from "./post";
export type { ReadMoreProps } from "./read-more";
export type { SocialProps } from "./socials";
export type { Tag } from "./tag";

BlogCard.tsx:

import { PostProps } from "@types"; // <== Cannot find module '@types' or its corresponding type declarations.ts(2307

Answer №1

Encountering a similar issue, it seems that the conflict arises between @types/ and default @type dependency imports (e.g. @types/react, @types/react-dom, @types/node, etc) located within the typically ignored node_modules directory (e.g. node_modules/@types/).

It is believed (though not confirmed) that even with manual path mapping in tsconfig.json, using configuration like;

"@types/*": ["types/*"]
, TypeScript may disregard this as it internally maps @types/ to only search within the node_modules folder.

Possible Resolution (?)

A potential solution is to add the following line to tsconfig.json:

{
  "compilerOptions": {
    // ...
    "typeRoots": [
      "./node_modules/@types",
      "./types"
    ]
  }
}

However, this did not work in my scenario. It would be beneficial to understand why.

Alternate Approach

To maintain consistency, I opted to map custom paths using @/ (with trailing slash) for distinguishing between officially installed dependencies (@type from node_modules) and project source code directories.

For instance: Set up the following paths in tsconfig.json:

{
  "compilerOptions": {
    // ...
    "paths": [
      "@/components/*": ["./src/components/*"],
      "@/types/*": ["./src/types/*"]
    ]
  }
}

Then, within a source code script file (e.g. .tsx), import types and components using the shorthand prefix @/:

import { SomeType } from "@/types/someType";
import SomeComponent from "@/components/some-component/SomeComponent";

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

Group data by two fields with distinct values in MongoDB

I have developed a Typescript Node.js application and I am looking to organize documents by two fields, "one_id" and "two_id", based on a specific "one_id" value. Below is the data within my collection: { "_id":"5a8b2953007a1922f00124fd", "one_id ...

imported classes from a module cannot be accessed within the same module

Here is some TypeScript code that I wrote: Within my module, I am importing a library called ts-events. import {SyncEvent} from 'ts-events' module MyModule{ export class MyService{ } } In the same module but in a different file, I'm ...

Simultaneously iterate through two recursive arrays (each containing another array) using JavaScript

I have two sets of arrays composed of objects, each of which may contain another set of arrays. How can I efficiently iterate through both arrays and compare them? interface items { name:string; subItems:items[]; value:string; } Array A=['parent1&ap ...

Guide to verifying a value within a JSON object in Ionic 2

Is there a way to check the value of "no_cover" in thumbnail[0] and replace it with asset/sss.jpg in order to display on the listpage? I have attempted to include <img src="{{item.LINKS.thumbnail[0]}}"> in Listpage.html, but it only shows the thumbna ...

Attempting to create a cookie in getServerSideProps with next.js

Trying to set a cookie in getServerSideProps has been a bit tricky for me. Even though I can successfully read it using `req.headers.cookie`, setting it doesn't seem to work. I've tried different methods, like using libraries such as cookies-next ...

Exploring nested JSON objects within an array using ngFor directive

My application uses Angular 6 and Firebase. I am trying to showcase a list of all appointments. Below is my approach: service.ts getRDV() { this.rdvList = this.firebase.list('/rdv'); return this.rdvList; } Model: export class RDV { key: ...

The argument provided, 'Item', cannot be assigned to the parameter, 'string'. TS2345 error encountered

Encountering an issue with type 'string'. Error code TS2345 Problem: Argument of type 'Item' is not compatible with parameter of type 'string'. TS2345 filter(resortList:ResortResult[], selectedFilters:SelectedFilters) { ...

Discover the mistake during the creation of the next.js application build

Trying to build my next.js file, but encountering an error: ./pages/city/[city].js 21:20 Error: React Hook "useRouter" is called in function "city" that is neither a React function component nor a custom React Hook function. React ...

Bringing together projects utilizing varying Typescript versions within Visual Studio 2015

When working with VS2015-SP2, imagine a solution that contains two typescript projects. One project is using version 1.5 and the other is using version 1.7. How will the compiler handle this situation? ...

Enable a fraction of a category

Imagine having a structure like this interface User { name: string; email: string; } along with a function like this updateUser(user: User) { } As currently defined, updateUser cannot accept only a name (updateUser({name: 'Anna'} would fa ...

Retrieve the text content of the <ul> <li> elements following a click on them

Currently, I am able to pass the .innerTXT of any item I click in my list of items. However, when I click on a nested item like statistics -> tests, I want to display the entire path and not just 'tests'. Can someone assist me in resolving this i ...

What is the method by which Next API Route manages multiple simultaneous requests?

Imagine I've developed an application with an API route. Let's say two users submit requests to upload a file to an S3 bucket through that API, and then my backend needs more than 2 minutes to process the file. How is this situation managed? How ...

How can I retrieve List<T> from a Razor Page using TypeScript?

Within my ViewModel, I have an Items collection: public class ItemViewModel{ public List<Item> Items {get;set;} } In the Index.cshtml file: @if(Model.Items != null){ <li><a id="item-id-link" href="#" data-items="@Model.Items"> ...

Explanation of TypeScript typings for JavaScript libraries API

Currently, I am in the process of building an Express.js application using TypeScript. By installing @types and referring to various resources, I managed to create a functional program. However, my main query revolves around locating comprehensive document ...

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 ...

Pattern matching to eliminate line breaks and tabs

Hey there, I'm working with a string: "BALCONI \n\n\t\t\t\t10-pack MixMax chocolade cakejes" and trying to tidy it up by removing unnecessary tabs and new lines. I attempted using .replace(/(\n\t)/g, '&apo ...

The use of anonymous arrow functions results in Fast Refresh not maintaining local component state

I am facing an issue with the code in my pages/index.js file: import React from 'react'; import dynamic from 'next/dynamic'; const TVChartContainer = dynamic( () => import('../components/TVChartContainer').then ...

Strange error message regarding ES6 promises that is difficult to interpret

Snippet getToken(authCode: string): Promise<Token> { return fetch(tokenUrl, { method: "POST" }).then(res => res.json()).then(json => { if (json["error"]) { return Promise.reject(json); } return new Token ...

Changing function arguments in TypeScript using the spread operator

Could the Tuple spreading syntax in Typescript be utilized to consolidate these function overloads? The challenge lies in the necessity to refactor the function arguments into new types. type Type = TString | TNumber type TString = { tag: 'string&apos ...

"Extra loader required to manage output from these loaders." error encountered in React and Typescript

After successfully writing package 1 in Typescript and running mocha tests, I confidently pushed the code to a git provider. I then proceeded to pull the code via npm into package 2. However, when attempting to run React with Typescript on package 2, I enc ...