Turn on strict: true first. It enables a group of checks, and new projects should always use it.
The most important checks inside strict:
strictNullCheckskeepsnullandundefinedout of every type unless you add them. So you must handle missing values. Example:document.getElementById("x").focus()errors, because the element may benull.noImplicitAnygives an error when TypeScript cannot infer a type and would silently useany. Example:function f(x) {}errors until you typex.strictFunctionTypeschecks function parameter types more strictly when you assign one function to another. Example: a(x: string) => voidhandler cannot be used where a handler forstring | numberis expected.useUnknownInCatchVariablesmakes thecatchvariableunknowninstead ofany. Example: incatch (e), you must checke instanceof Errorbefore readinge.message.
Useful options outside strict:
noUncheckedIndexedAccessaddsundefinedto reads from arrays and index signatures. Example:arr[0]isT | undefined, because the array may be empty.exactOptionalPropertyTypesseparates a missing key from a key set toundefined. Example: withname?: string, writing{ name: undefined }becomes an error.noImplicitReturnsgives an error when some code paths in a function return a value and others do not. Example: anifthat returns, with noreturnafter it.
For bundler setups, isolatedModules makes sure each file can be compiled on its own. Tools like Babel, esbuild and SWC compile one file at a time and need this.
- Use
strict: trueas the baseline for every new project. strictNullChecksmeans you must handlenullandundefined.noImplicitAnystops variables from silently becomingany.noUncheckedIndexedAccessaddsundefinedto array and index reads, likearr[0].isolatedModulesmakes each file compile on its own, for tools that compile one file at a time.
Read more
- TSConfig reference (https://www.typescriptlang.org/tsconfig)typescriptlang.org