tsconfig flags to prevent common errors
Even thought it’s ostensibly just a compiler, TypeScript also includes a bunch of flags that helps prevent common code errors. I end up reusing these in most TypeScript projects I work on, so I figured I’d just document them here for future reference.
{
"strict": true,
"noFallthroughCasesInSwitch": true,
"noImplicitOverride": true,
"noImplicitReturns": true,
"noUncheckedIndexedAccess": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"forceConsistentCasingInFileNames": true,
"verbatimModuleSyntax": true
}
Here’s a short explanation of what each flag does
strictenables a bunch of other flags; enabling this is really the bare minimum.alwaysStrictuses strict mode emits"use strict"in each file.noImplicitAnyraises an error if lack of type annotations would lead it to inferany.noImplitictThisraises an error if a reference tothishas an inferredanytype.strictBindCallApplycorrectly types thebind,callandapplymethods on functions; otherwise, they accept and returnany.strictFunctionTypestreats function arguments as contravariant rather than bivariant.strictNullCheckstreatsundefinedandnullas their own distinct types, forbidding e.g. accessing a property of a type that might be undefined.strictPropertyInitializationraises an error when a class property that isn’t optional is not set by default or in the constructor.useUnknownInCatchVariablesusesunknownrather thananyas the type of the exception in a catch clause.
noFallthroughCasesInSwitchforces non-empty cases in switch statements to end with abreakorreturn.noImplicitOverrideraises an error if a subclass overrides a method in a superclass without being annotated withoverride.noImplicitReturnsraises an error if only some code paths in a function return a value.noUncheckedIndexAccessuses a union withundefinedwhen accessing values of objects with unknown keys, such as objects that act as indexes or arrays of unknown length. This can be somewhat annoying, since you now need to check forundefinedevery time, but it’s safer.noUnusedLocalsraises an error when a local variable is declared but never used; the error can be suppressed by prefixing the variable name with an underscore.noUnusedParametersraises an error when a function parameter is declared but never used; the error can be suppressed by prefixing the variable name with an underscore.forceConsistentCasingInFileNamesraises an error if the casing of an import specifier (”foo.js”) differs from the file on disk (Foo.js).verbatimModuleSyntaxensures that type-only imports are explicitly annotated as such (since they’re erased at runtime, they won’t behave the same as value imports if the module causes side effects). ReplacesimportsNotUsedAsValues.