'How to correctly import custom types in typescript

I have custom type in src/@types/app.d.ts ( export type AuthKeyT = string )

I would like to use it in tsx react file (using import { AuthKeyT } from '@types/app'), but I am getting an error:

Cannot import type declaration files. Consider importing 'app' instead of '@types/app'

So, when I use import { AuthKeyT } from 'app' I am getting:

Cannot find module 'app'.

So.. what is wrong? How should I import custom type?

I am using typescript 3.7.2 in react app.



Solution 1:[1]

You're facing this error because @types/... is a global import. For example import { AuthKeyT } from '@types/app' means your're trying to import from @types that is in node_modules.

You can fix this by changing @types to something like @customTypes or by changing the path for your types folder something like @src/types... while importing.

Solution 2:[2]

You can also add path to your compilterOptons in the tsconfig.json like this:

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

and then import { AuthKeyT } from 'types/app'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nishant Singh
Solution 2 FelixTellmann