TypeScript adds static typing to JavaScript, which finds errors before running the code. To set up a TypeScript project, start by installing the TypeScript compiler and creating a tsconfig.json file. This configuration defines how TypeScript should process the code. The setup works with standard JavaScript environments like browsers or Node.js.
Initialize the Project Directory
Initialize the project directory to separate your TypeScript code from other files on your system. This structure manages dependencies, configuration files, and source code in one place. The package.json file tracks installed packages and defines scripts for tasks like building and testing the project.
mkdir my-typescript-appcd my-typescript-appExplanation:
- mkdir creates a new directory.
- cd changes into that directory.
- npm init -y creates a package.json file with default values using valid JSON syntax.
Then initialize it with a package.json file:
npm init -yExplanation:
- npm install follows CLI conventions.
- --save-dev adds TypeScript as a development dependency in package.json.
Install TypeScript Compiler
Installing the TypeScript compiler allows projects to transform .ts files into JavaScript. This adds the compiler as a development dependency and prepares the environment to type check and building processes. The compiler runs with project-specific settings and avoids global version conflicts.
npm install typescript --save-devExplanation:
- npm install installs packages from the npm registry.
- --save-dev adds the package to the devDependencies section of package.json.
After installation, a tsc command becomes available locally in node_modules/.bin.
Generate a tsconfig.json File
The tsconfig.json file defines how the TypeScript compiler processes source files. It sets paths, module targets, and strictness options for type checking. This configuration organizes the project structure and controls the emitted JavaScript output.
Run the following command to generate a base compiler configuration:
npx tsc --initExplanation:
- npx runs the local TypeScript binary if available.
- tsc --init generates a default tsconfig.json file in the project root.
- The strict option in tsconfig.json enables full type-checking mode, which activates rules like noImplicitAny and strictNullChecks.
This creates tsconfig.json to control how TypeScript compiles source files. Key fields include:
{"compilerOptions": {"target": "ES6","module": "commonjs","outDir": "./dist","rootDir": "./src","strict": true,"esModuleInterop": true},"include": ["src"]}Explanation:
- target: ECMAScript version
- module: Module system (e.g., CommonJS for Node.js)
- outDir: Output directory for compiled JS
- rootDir: Source code directory
- strict: Enables all strict type-checking options
- esModuleInterop: Ensures compatibility with CommonJS modules
Create Project Structure
A clear folder structure manages source files, output builds, and configuration in one place. TypeScript compiles files from the src directory and writes the output to the dist directory. The tsconfig.json and package.json files define project settings and dependencies. Create the following folder structure:
my-typescript-app/├── src/│ └── index.ts├── dist/├── package.json└── tsconfig.jsonExplanation:
- This structure follows a convention where src/ holds input .ts files and dist/ holds output .js files.
- tsconfig.json uses rootDir and outDir to map this layout.
Use a sample function to verify that the TypeScript setup compiles and executes correctly. This example defines a typed arrow function, passes a string argument, and logs the result. Add sample TypeScript code to src/index.ts:
const greet = (name: string): string => {return `Hello, ${name}`;};
console.log(greet('TypeScript'));Explanation:
- Arrow function syntax: (name: string): string => {} defines parameter and return types.
- Template literals use backticks for string interpolation.
Compile TypeScript Code
The TypeScript compiler reads source files based on the settings in tsconfig.json and generates JavaScript output. Running the compiler processes all included .ts files and places the results in the output directory. This confirms that the configuration and code compile without errors. Run the TypeScript compiler:
npx tscExplanation:
- npx executes the local version of the tsc command from node_modules/.bin.
- No arguments use the configuration defined in tsconfig.json by default.
This compiles .ts files in src/ and outputs .js files in dist/.
Run the Compiled Output
After compiling the TypeScript code, the JavaScript output appears in the configured output directory. Use Node.js to execute the generated .js file. This checks if the build process succeeded and whether the program behaves as expected at runtime. Use Node.js to execute the generated JavaScript:
node dist/index.jsExplanation:
- node runs JavaScript files using the Node.js runtime.
- The path dist/index.js points to the output generated by the TypeScript compiler.
Expected output:
Hello, TypeScript