Javascript is known for being a dynamically typed language, meaning that you don’t need to specify the type of variables when you declare them. This gives developers flexibility but can also lead to bugs, especially in large codebases. statically typed languages like Java, C++, Rust, and Go require that the type of each variable be declared explicitly.
TypeScript brings the best of both worlds. It adds static types to JavaScript, making the code more predictable and robust.
TypeScript Basics: Getting Started
1. Installing the TypeScript Compiler
First, you’ll need to install TypeScript globally on your machine. You can do this using npm (Node Package Manager):
bashCopy codesudo npm install -g typescript
To verify the installation, check the TypeScript version using the following command:
bashCopy codetsc -v
2. Creating a Simple TypeScript File
Let’s create a simple TypeScript file to illustrate how TypeScript differs from JavaScript. TypeScript uses the .ts extension for regular TypeScript files and .tsx for files that use JSX (e.g., React).
typescriptCopy code// index.ts
let id: number = 5;
In this example, id is explicitly declared as a number. This is different from JavaScript, where you wouldn’t declare the type, and id could be reassigned to any type of value.
3. Compiling TypeScript to JavaScript
To compile the TypeScript file to JavaScript, open your terminal and run:
bashCopy codetsc index.ts
This command generates a JavaScript file index.js. To enable TypeScript’s “watch” mode, which automatically compiles your code when changes are detected, use:
bashCopy codetsc --watch index.ts
4. Configuring TypeScript with tsconfig.json
One of the strengths of TypeScript is its configurability. You can set up a tsconfig.json file to define how TypeScript should compile your project. Run the following command to generate this file:
bashCopy codetsc --init
The tsconfig.json file allows you to set various options, such as:
target: Defines the version of JavaScript that the TypeScript compiler will output. You can target ES5, ES6, or even newer versions.outDir: Specifies the output directory for the compiled JavaScript files. For example, you might set this to./dist.rootDir: Defines the root directory for your TypeScript source files. For instance, you might store your TypeScript files in./src.
Here’s an example of how you might structure a basic TypeScript project:
perlCopy codemy-project/
├── dist/ # Compiled JavaScript files
├── src/ # TypeScript source files
│ └── index.ts # Main TypeScript file
└── tsconfig.json # TypeScript configuration file
In the tsconfig.json file, you can define the outDir and rootDir like this:
jsonCopy code{
"compilerOptions": {
"target": "es6",
"outDir": "./dist",
"rootDir": "./src"
}
}
Once you move your index.ts file into the src/ folder, running tsc will compile the code and generate the index.js file in the dist/ folder.