TypeScript
Summary - Emit
Write a library build configuration with emit options.
Summary: library build config
A library build config combines four emit parts: outDir sets the output directory, declaration: true produces .d.ts, sourceMap: true adds a debug map, and when needed emitDecoratorMetadata: true carries decorator metadata to runtime. Together they produce a library that is consumable and debuggable.
{
"compilerOptions": {
"outDir": "dist",
"declaration": true,
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true
}
}
These settings are the skeleton of libraries published to npm.
Exercise Validate the library config
Write a validateLibraryConfig function that checks a config object's declaration and outDir fields as required, and sourceMap and emitDecoratorMetadata as optional. Push to an errors array for missing required fields. Print the error count for the config { declaration: true, outDir: "dist", sourceMap: true }.
Show example solution
type LibraryConfig = {
declaration?: boolean;
outDir?: string;
sourceMap?: boolean;
emitDecoratorMetadata?: boolean;
};
function validateLibraryConfig(config: LibraryConfig): string[] {
const errors: string[] = [];
if (!config.declaration) errors.push("declaration must be true");
if (!config.outDir) errors.push("outDir must be set");
return errors;
}
const config = { declaration: true, outDir: "dist", sourceMap: true };
console.log(validateLibraryConfig(config).length);
Test yourself
-
Which options does a library config include?
- Only noEmit and inlineSourceMap
- Only emitDeclarationOnly and rootDir
- Only outDir and noEmit
- outDir, declaration, sourceMap, and emitDecoratorMetadata when needed
Show answer
outDir, declaration, sourceMap, and emitDecoratorMetadata when needed — A library config combines output, declaration, source map, and when needed decorator metadata; noEmit produces no output so it is not suited for a library.
-
Produce declarations for the library
{
"compilerOptions": {
"outDir": "dist",
"____": true
}
}
Show answer
{
"compilerOptions": {
"outDir": "dist",
"declaration": true
}
}
-
Library config parts
- outDir
- sets the output directory
- declaration: true
- produces .d.ts
- sourceMap: true
- debug map
- emitDecoratorMetadata: true
- carries decorator type info
Next lesson: Type complexity