Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 404
javad26897 Avatar asked Apr 19 '20 16:04

javad26897


People also ask

Can I use import in TypeScript?

There are two ways to solve this: Using import = require() and setting the esModuleInterop property to true in the TypeScript Compiler configuration file. The import = require() syntax uses the exports object as the value for the import itself, allowing you to use each vector class.


Video Answer


2 Answers

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.

like image 137
Nishant Singh Avatar answered Oct 08 '22 15:10

Nishant Singh


As the error says, you can't import a .d.ts file in TypeScript.

import ... from 'app' mean implicitly import ... from 'app.ts' or this file don't exist so you get the second error.

If you want to use your types using this import, you have to write them in a simple .ts file like that:

src/@types/app.ts:

export type AuthKeyT = string

With this structure you will be able to import this type using:

import { AuthKeyT } from 'app'
like image 4
johannchopin Avatar answered Oct 08 '22 16:10

johannchopin