Typescript checking
Type-checking your TypeScript code is crucial for catching errors early and ensuring code quality. This article explains how to use the "typecheck" script in package.json to validate your TypeScript code without generating output files. Streamline your development process with this simple yet powerful tool!
1. Format code by VS code and Prettier
Add this command into the scripts section in your package.json:
json{ "scripts": { "typecheck": "tsc --project tsconfig.json --pretty --noEmit && echo" } }
Notes: Ensure you have the tsconfig.json in your root of source code.
Now we have the command for checking type issues in all source code files:
bashyarn typecheck
the outputs:
bashtuanh@VNNOT02369:~/me/build2earn-next15 (main)$ yarn typecheck yarn run v1.22.19 $ tsc --project tsconfig.json --pretty --noEmit && echo Done in 1.57s.
2. Explain the script
tsc This is the TypeScript Compiler command.
--project tsconfig.json This tells the TypeScript Compiler to use the specified tsconfig.json file to determine the configuration for the type-checking process.
--pretty This enables formatted, colorful output for better readability in the terminal.
--noEmit This ensures that the TypeScript Compiler performs type-checking without generating any output files. It's useful when you only want to verify the types and not create compiled .js files.
&& echo This runs another command after the type-checking completes. In this case, it runs echo, which effectively does nothing but ensures the script finishes successfully without additional actions.
3. Purpose
This script is commonly used to:
- Verify TypeScript types before committing or deploying code.
- Integrate type-checking into CI/CD pipelines.
- Ensure code adheres to the TypeScript type system without emitting compiled files.