Sub topic 3
Unknown Catch Variables and Strict Project Configuration
Assume basic TypeScript syntax, JSON, and running tsc with Node.js installed. This chapter focuses on compiler settings that make errors visible across a project.
Unknown catch variables and `alwaysStrict`
With useUnknownInCatchVariables, a caught value has type unknown. You must check its type before using it. This is safer because JavaScript can throw strings, numbers, or other values.
try {
JSON.parse("{");
} catch (error) {
if (error instanceof Error) {
console.error(error.message);
} else {
console.error("Unknown failure", error);
}
}alwaysStrict makes TypeScript parse every file in strict mode and emits "use strict" for script files. It is useful when older JavaScript files might otherwise allow unsafe behavior.
Useful checks outside `strict`
Some valuable checks are disabled by strict:
noUncheckedIndexedAccessaddsundefinedto indexed reads such asitems[0].noImplicitOverriderequiresoverridewhen a subclass replaces a base-class method.noPropertyAccessFromIndexSignaturerequires bracket notation for index-signature properties.
Enable these when the extra safety is worth fixing more errors.
Sharing settings with `extends`
A shared tsconfig.base.json can hold common rules. Each package extends it and defines its own paths.
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "dist",
"rootDir": "src"
},
"include": ["src"]
}Relative paths in the child configuration are resolved relative to that child file.
Interop, speed, and isolated compilation
esModuleInterop improves default-import compatibility with CommonJS packages and emits helper code when needed. skipLibCheck skips checking declaration files, which can speed builds but hide conflicting library types. isolatedModules reports code that cannot be safely transformed one file at a time, as required by some transpilers.
Moving an existing project to strict mode
Enable strict first, then group and fix errors by category. If the migration is too large, temporarily disable one flag:
{
"compilerOptions": {
"strict": true,
"noImplicitAny": false
}
}Track that exception and re-enable it after adding annotations and narrowing nullable values.
Seeing the effective configuration
Use these commands to find what TypeScript really uses:
npx tsc --showConfig
npx tsc --listFilesThe first shows inherited and expanded options. The second shows every input file.
Project references
Large repositories can split packages into composite projects. Set "composite": true, then connect projects with references. TypeScript can build dependencies in order and reuse their outputs.
Exercise
Why must code inside a catch block check error instanceof Error before reading error.message?
Show answer
Because the caught value is unknown and might not be an Error object.