Why TypeScript? Type Safety for JavaScript Projects

TypeScript adds static typing to JavaScript, catching errors at compile time rather than runtime.

## Why TypeScript?

- Catch bugs before they hit production
- Better IDE support (autocomplete, refactoring)
- Self-documenting code with types
- Safer refactoring
- Easier onboarding for large teams

## Basic Types

```typescript
// Primitives
let name: string = 'John';
let age: number = 30;
let active: boolean = true;

// Arrays
let items: string[] = ['a', 'b', 'c'];
let numbers: number[] = [1, 2, 3];

// Objects
interface User {
 id: number;
 name: string;
 email?: string;  // Optional
 readonly createdAt: Date;
}

// Functions
function greet(user: User): string {
 return `Hello, ${user.name}`;
}
```

## Advanced Types

```typescript
// Union types
type Status = 'active' | 'inactive' | 'pending';

// Generics
function getFirst<T>(arr: T[]): T | undefined {
 return arr[0];
}

// Utility types
type PartialUser = Partial<User>;
type UserKeys = keyof User;
```

## Setting Up

```bash
npm install -D typescript
npx tsc --init
```

## tsconfig.json Key Options

```json
{
 "compilerOptions": {
   "target": "ES2020",
   "module": "ESNext",
   "strict": true,
   "noImplicitAny": true,
   "strictNullChecks": true
 }
}
```

## Conclusion

TypeScript pays dividends on projects of any size. Start with strict mode on and gradually type your codebase.

评论
暂无评论