Linter for TypeScript
Tools do static analysis without running code. Quality and uniformity in coding depend on these tools. TypeScript provides a static typing option to catch problems early at build time, reducing bugs. TypeScript lints JavaScript better than type-incomplete linters.
Engineering teams worldwide (Google, Microsoft, Facebook) use linters because static analysis improves code quality and understandability. The compiler catches errors rather than runtime failure, improving documentation (function signatures provide precise documentation), and improving developer tooling by improving autocompletion and refactoring.
Static analysis by linters like TSLint and ESLint detects faults and possible issues, assuring application code quality and consistency.
TSLint and ESLint for Consistency
In the past, TypeScript projects relied heavily on TSLint to ensure code consistency and quality. To find possible issues, it uses static analysis.
TSLint Installation and Setup
To install TSLint globally, one would use the following command:
npm install -g tslint
TSLint is configured via a tslint.json
file. To initialise a default configuration, the following command is used:
tslint --init
After configuration, a file can be checked for possible errors using:
tslint filename.ts
Tslint:recommended
is a reliable, opinionated set of extensible rules for mainstream TypeScript development. This makes a reasonable initial setup possible.
Configuring TSLint Rules (, , )
A tslint.json
file dictates the rules enforced by the linter. Basic tslint.json
setup designed to enforce important consistency rules, including no-any
, curly
, and quotemark
.
In a basic configuration, some important code quality rules look like this:
Rule Name | Description | Purpose in Code Quality |
no-any | Prevents usages of any as a type declaration. | Forces developers to use explicit types, reducing reliance on the type escape hatch any , thereby maximising type safety and leveraging the core benefit of TypeScript. |
curly | Requires curly braces for if/else/for/do/while statements. | Enforces structured control flow, improving readability and preventing potential bugs where logic might accidentally fall outside the intended block. |
quotemark | Requires consistent quote usage (e.g., double quotes for strings). | Ensures stylistic uniformity, which is a key component of consistency. |
A basic tslint.json
setup to enforce these rules looks like this:
Code: tslint.json
(Basic setup)
{
"rules": {
"no-any": true,
"curly": true,
"quotemark": [true, "double"]
}
}
Example: Enforcing TSLint Rules
Consider a TypeScript file, bad-code.ts
, that violates these configured rules:
Code: bad-code.ts
(Input)
const magicNumber: any = 50; // Violates no-any
if (magicNumber > 10)
console.log('High'); // Violates curly
const message = 'Hello World'; // Violates quotemark
The following problems (conceptual output, since particular linter output is not provide, focussing on enforcement) would be found when TSLint is run against this file with the above configuration:
Output: (Conceptual Lint Report)
bad-code.ts:1:16 - error: Disallows usages of any as a type declaration. (no-any)
bad-code.ts:3:22 - error: Statements must be enclosed in curly braces. (curly)
bad-code.ts:6:17 - error: Requires double quotes for string literals. (quotemark)
This illustration demonstrates how type safety violations, structural irregularities, and stylistic differences are detected via static analysis prior to compilation.
Transition to ESLint
Although TSLint was widely used, the cooperation between the ESLint and TypeScript teams has made ESLint the de facto linter for TypeScript. For ESLint to handle TypeScript code, certain packages are needed:
eslint
: The core linter.@typescript-eslint/parser
: Allows ESLint to understand.ts
and.tsx
files.@typescript-eslint/eslint-plugin
: Provides the TypeScript-specific lint rules.eslint-plugin-react
: If needed, for React rules.
The packages are installed as development dependencies, noting that ESLint refers to packages containing lint rules as “plugins”.
Code: ESLint Installation
npm i eslint eslint-plugin-react @typescript-eslint/parser @typescript-eslint/eslint-plugin
Configuring ESLint
ESLint configuration usually resides in a .eslintrc.js
file and links directly to the project’s tsconfig.json
for type awareness.
Code: .eslintrc.js
(Configuration)
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: './tsconfig.json',
},
plugins: ['@typescript-eslint'],
extends: [
'plugin:react/recommended',
'plugin:@typescript-eslint/recommended',
],
rules: {
// Overwrite rules specified from the extended configs e.g.
// "@typescript-eslint/explicit-function-return-type": "off",
}
}
Integrating Linters into the Build Process
In order to guarantee that code quality checks are required prior to code acceptance, liners are usually incorporated into the development cycle.
To run ESLint validation, a script can be added to package.json
:
Code: package.json
(Lint Script)
{
"scripts": {
"lint": "eslint src/**"
}
}
This allows developers to run the linter validation via npm run lint
.
Furthermore, for developers using Visual Studio Code (VSCode), an extension is available, and configuration can be set in settings.json
to enable automatic fixing (autoFix
) for TypeScript and TypeScript React files.
Code: settings.json
(VSCode Integration)
"eslint.validate": [
"javascript",
"javascriptreact",
{"language": "typescript", "autoFix": true },
{"language": "typescriptreact", "autoFix": true }
],
Prettier for Automated Code Formatting
Tools like Prettier concentrate just on automated code formatting, whereas linters guarantee code quality and stylistic accuracy (such as quote usage and brace alignment). Facebook created the wonderful tool Prettier, which greatly streamlines code formatting.
By assisting a team in achieving high formatting uniformity, Prettier lessens the cognitive strain on developers, allowing them to concentrate on the code’s true purpose.
Prettier Setup and Configuration
Prettier is installed as a development dependency:
npm install prettier -D
Configuration often involves defining scripts in package.json
to manage checking (for CI/build servers) and writing/fixing (for local development).
Code: package.json
(Prettier Scripts)
"prettier:base": "prettier --parser typescript --single-quote",
"prettier:check": "npm run prettier:base -- --list-different \"src/**/*.{ts,tsx}\"",
"prettier:write": "npm run prettier:base -- --write \"src/**/*.{ts,tsx}\""
Take note of prettier:base
‘s --single-quote
option. In accordance with the norms followed by many JavaScript teams (such as AirBnB, Facebook/React, and npm), the Prettier team typically suggests using single quotes.
Integrating Prettier via Husky
Husky, a program made to execute scripts prior to Git actions (such as commits or pushes), is frequently used to integrate Prettier in order to guarantee consistency. By automatically formatting files or performing lint checks prior to the code being completed, Husky guards against bad commits.
To set up Husky:
npm install husky -D
A pre-commit hook is then configured in package.json
to run the formatting script automatically:
Code: package.json
(Husky Pre-commit Hook)
"precommit": "npm run prettier:write",
Now, npm run prettier:write
automatically runs and formats any impacted files whenever a developer submits code. Modified files show up in the git log if formatting changes are done. This enables the developer to either update the most recent commit to smoothly include the formatting changes or commit the changes (for example, with a comment pretty
) if they have already pushed their code.
Projects can effectively maintain high code quality standards throughout the development lifecycle by utilising static analysis with linters (TSLint/ESLint) for bug identification and policy enforcement, and combining this with Prettier for automated style consistency.