TypeScript: Basics of the Type System
1. Introduction to TypeScript
Developed by Microsoft, TypeScript is a superset of JavaScript. It provides a static type system, which is essential for large-scale application development.
- Features: Static type checking, support for modern JS syntax, and deep integration with development tools (IDEs).
- Advantages: Code auto-completion, ease of refactoring, and prevention of runtime errors.
- Key Point: All valid JavaScript is also valid TypeScript (Substitutable).
2. Starting a Project
The most common way to start is by using the tsc command.
# Global installation
npm install -g typescript
# Initialize project (creates tsconfig.json)
tsc --init
3. Core Syntax: Type Declarations
// Basic type declarations
let name: string = "TypeScript User";
const age: number = 25;
// Interface
interface User {
id: number;
username: string;
isAdmin: boolean;
}
const loginUser: User = {
id: 1,
username: "dev_user",
isAdmin: true
};
// Function types
function add(a: number, b: number): number {
return a + b;
}
4. Why Use TypeScript?
By preventing errors like "undefined is not a function" during compile time, it significantly boosts productivity compared to JavaScript's dynamic typing nature.