IntermediateLesson 11 of 15
Modules, Type Declarations & tsconfig – TypeScript
import type, @types packages, .d.ts files and important compiler options.
TypeScript uses the same ES modules as JavaScript. You export and import types the same way; with import type you make it clear that the import is only needed by the compiler and disappears from the JavaScript.
// nutzer.ts
export interface Nutzer {
id: number;
name: string;
}
export function neuerNutzer(name: string): Nutzer {
return { id: Date.now(), name };
}
// main.ts
import { neuerNutzer, type Nutzer } from "./nutzer.js";
import type { Nutzer as N2 } from "./nutzer.js"; // is removed completely
const n: Nutzer = neuerNutzer("Ada");WarningWith Node.js and ES modules (
"module": "NodeNext") you write the extension .js in imports – even though the file is called .ts. TypeScript does not rewrite import paths; it checks them against the generated JavaScript.Libraries written in plain JavaScript need types. Many ship them; for others there are packages from the DefinitelyTyped project in the @types namespace. You write your own declarations in .d.ts files:
npm install express
npm install --save-dev @types/express @types/node// global.d.ts – types without implementation
declare const APP_VERSION: string; // injected by a bundler
declare module "*.svg" {
const pfad: string;
export default pfad;
}
interface Window {
meineApp: { debug: boolean }; // declaration merging: extends Window
}A sensible basic skeleton for the tsconfig.json of a Node project:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true,
"noUncheckedIndexedAccess": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true,
"outDir": "dist",
"rootDir": "src"
},
"include": ["src"]
}Tip
target determines which JavaScript is generated, lib which built-in types (DOM, ES2023 …) are known. For browser projects a bundler (Vite, esbuild) usually handles the conversion, and tsc --noEmit is used only for type checking.