typescript

Canonical reference for why TypeScript omits unused imports


If you have some code like this:

//other.js|ts

console.log("module sideffect") 
export function foo() {

}


//main.js|ts 
import {foo} from "./other"; // foo is not used  

console.log("do something else"); 

Then JavaScript and TypeScript behave differently in this scenario.

TypesScript will omit the import of "./other", and the console.log("module sideeffect") will not fire.

Whereas JavaScript will do the import and it will fire.

If on the other hand we do the import like:

import "./other"; 

The module side effects will fire.

There's a related question here:

Side effects in import statements

and here:

import module for side-effects with Typescript only targeting node

Which are both talking about this, but unfortunately both answers are now pointing to TypeScript documentation that no longer exists.

I'm looking for a canonical reason as to why TypeScript does this omission, and whether it's configurable behaviour. (One can imagine a scenario where code stops working because an import is no longer used).


Solution

  • whether it's configurable behaviour

    The relevant option is verbatimModuleSyntax. Its name is somewhat self-explanatory, and there are more details in the documentation if you follow that link, but in short it preserves all non-type imports as you wrote them.

    a canonical reason as to why TypeScript does this omission

    I couldn't find a concise explanation in the documentation, but the verbatimModuleSyntax option's description has some rationale, as did the release notes for related features: