Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is TypeScript top-level non-export code executed?

I am currently confused on when code in a file is actually executed an when it is not. If I have a file1.ts file like the following:

export interface myInterface {}
export function myFunction() {}
export const myConst: {}

// ... and more exports

// top-level non-exported code
if (condition) {
    myConst = ...
}

And a file2.ts containing one the following:

import { myInterface } from "./file1.ts"
import * from "./file1.ts"
import * as file1 from "./file1.ts"
import "./file1.ts"

How does the the behaviour differ? When is the top-level code that wasn't exported in file1.ts executed and when is it not executed? Is it executed even when only a specific export is imported (see first variant)?

This is making me crazy right now and I didn't find anything about it on the TypeScript handbook page for modules.


1 Answers

Multiple conditions determine if TypeScript module gets included in final, transpiled JavaScript files, or not:

  1. Kind of usage of imported variables in the your own code.
  2. Type of imported variables (class, interface, etc).
  3. Since TypeScript 2.8 compiler settings importsNotUsedAsValues to control the behavior.
  4. Since TypeScript 2.8 there is also new syntax import type and export type for modules that are explicitly excluded from final, compiled JavaScript files.

Check following section in the TypeScript 2.8 release notes for more details: Type-Only Imports and Export

like image 104
Nenad Avatar answered Jul 19 '26 07:07

Nenad