Typescript Export Was Not Found Error


The Problem

I recently encountered a fairly obscure error in a Typescript project, where I was exporting a type (via export type TypeName ...), and then importing it in another place with import {TypeName} from ... - and when running the project (it was actually a package), I encountered a strange error that TypeName was not found in the file where it was defined. It seemed very strange.

The solution

The way to solve it is to do import type {TypeName} from ... - note the "type" part. That's pretty much what was required.

But why?

There's a great article that explains the problem in understandable details: https://javascript.plainenglish.io/leveraging-type-only-imports-and-exports-with-typescript-3-8-5c1be8bd17fb but in short, types are not saved in transpiled code, but import can't always identify it's a type so the import might remain in place - so when transpiled code tries to import the type, it's not available because types are removed when transpiling the code.

The import type directive tells transpiler that the type is imported, so it will be removed from the transpiled code as well and the code will not try to look for it - more details at https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-export.