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

Ways to inform websocket client of authentication failure

Utilizing the (ws package) in Node.js to handle websockets, I leverage the "on upgrade" event to authenticate incoming clients based on a token provided as a URL parameter. Following the guide here, if the token is invalid/missing/expired, I utilize the fo ...

Dividing a JSON object into arrays containing keys and values within an Angular framework

I have a code snippet that involves receiving a JSON object of type Tenant from an API. I need to separate this object into keys and values within my function called tenantParser(). However, when I try to log displayedValues and displayedKeys, both show ...

Incorporating RecoilRoot into Next.js with the Next.js 13's App router approach architecture

In my Next.js project, I've opted to utilize Recoil for state management. Following the structure of src/app/pages.tsx (app router approach) in Next.js 13 for routing instead of the default _app.tsx method, I'm now faced with the challenge of wra ...

Is dynamic data supported by Next.js SSG?

I'm currently developing a web application with Next.js and I need clarification on how Static generated sites work. My project is a blog that necessitates a unique path for each blog entry in the database. If I were to statically generate my web appl ...

Show the textbox automatically when the checkbox is selected, otherwise keep the textbox hidden

Is it possible to display a textbox in javascript when a checkbox is already checked onLoad? And then hide the textbox if the checkbox is not checked onLoad? ...

Looking to retrieve selections when the inputValue changes in react-select?

I'm working with a react-select component and I would like to implement a feature where an API request is triggered as soon as the user starts typing in the react-select field. This request should fetch items related to the keyword entered by the user ...

What is the best way to manage multiple tsconfig files for an Angular application?

Our customer has requested that we have two separate applications (with navigation from appA to appB) in one single package for easier deployment. However, we face a challenge as one section is coded in typescript with jQuery and the other is built in Ang ...

What is the best way to retain all checkbox selections from a form upon submission?

I have a batch of checkboxes that correspond to the profiles I intend to store in the database. HTML: <tr *ngFor="let profile of profiles | async"> <input type='checkbox' name="profiles" value='{{profile.id}}' ng-model=&apo ...

"Alert in Javascript executing prematurely prior to initiating the function for sending a get request

private validateURL(url: string) { let isValid = false; this.$http.get(url).then( (data) => { console.log('success'); isValid = true; } ).catch( (reason) => { console. ...

What are the best methods for implementing runtime type checking in JavaScript?

Utilizing either TypeScript or Facebook's Flow (type), I am empowered to statically assign types to variables like this: function add (x: integer, y: integer) { ... } Both TypeScript and Flow are able to identify and prevent incorrect invocations su ...

Merging all Angular 2 project files into a single app.js document

I've scoured the depths of the internet for an answer to this burning question: How can I merge all my Angular 2 code, along with its dependencies, into a single file? Although this query has been posed countless times before, I bring a fresh perspect ...

Prisma data is not being returned as an array in getServerProps with React Next.js

My Journey with Next.js and Prisma Having recently grasped the concept of getServerProps, I embarked on a project that involved retrieving data from a PostgreSQL database using Prisma. However, despite diligently following the syntax rules outlined in the ...

Using a static enum in a different class in TypeScript: A guide

After referencing this question and answer on Stack Overflow about setting a static enum inside a TypeScript class, I decided to create my own enum and implement it as a static property in my class. Here is how I did it: /* Input.ts */ enum INPUT_TYPE { T ...

Using Typescript: Including an additional argument

While experimenting with the code provided in the documentation interface Point { x: number; y: number; } function getX(p: Point) { return p.x; } class CPoint { x: number; y: number; constructor(x: number, y: num ...

Ways to extract information from an Object and save it into an array

In my Angular2 project, I am working on retrieving JSON data to get all the rooms and store them in an array. Below is the code for the RoomlistService that helps me fetch the correct JSON file: @Injectable() export class RoomlistService { constructor( ...

Utilize the ESLint plugin to manage unresolved import paths in Next.js modules

Utilizing module import from next and attempting to import a component as shown below: import Navbar from '@/components/Navbar/Navbar'; Upon running npm run lint, an error is returned stating: 1:20 Error: Unable to resolve path to module &apo ...

Enhancing SEO with nextJs ServerSideProps for optimized HTML rendering

Having an issue with rendering HTML output in AG-Grid using NextJS getServerSideProps. When checking the source code, the rendered HTML is not there for SEO purposes. However, if I output the "staff" array to a div, then the HTML is visible in the source ...

Angular error: Attempting to access the value property of an undefined object

When attempting to delete a row from a table, an error occurred stating "TypeError: Cannot read property 'value' of undefined" after placing the delete button at the end of a row. I watched this video tutorial for guidance on deleting a row witho ...

Encountering an anomaly in persistent redux while using NEXT.JS

I recently made some updates to my ecommerce store, including adding login and register options. To ensure that user tokens are saved even after a page refresh, I decided to implement redux-persist. However, I encountered an issue where the design breaks a ...

Unable to replace default typography in MUI with custom typography theme on Next.js

In my Next.js React project, I am utilizing Material-UI (MUI) with a customized theme. Although the colors from the theme are being applied successfully, I am encountering difficulty in adjusting the default font sizes of H2 and H5 elements. Even though I ...