# TypeScript 완벽 가이드
## 1. TypeScript란?
JavaScript에 타입을 추가한 언어. 컴파일 시점에 오류를 잡아줍니다.
## 2. 설치 및 설정
```bash
npm install -D typescript
npx tsc --init
```
## 3. 기본 타입
```ts
let name: string = "Kim";
let age: number = 25;
let isActive: boolean = true;
let data: any = "anything";
let list: number[] = [1, 2, 3];
let tuple: [string, number] = ["hello", 10];
```
## 4. 함수 타입
```ts
function add(a: number, b: number): number {
return a + b;
}
const greet = (name: string): void => {
console.log("Hello " + name);
};
// 옵셔널 파라미터
function log(msg: string, userId?: number): void {
console.log(msg, userId);
}
```
## 5. 인터페이스
```ts
interface User {
id: number;
name: string;
email?: string; // 옵셔널
readonly createdAt: Date; // 읽기전용
}
const user: User = {
id: 1,
name: "Kim",
createdAt: new Date()
};
```
## 6. Type Alias
```ts
type ID = string | number;
type Status = "pending" | "active" | "deleted";
type Point = {
x: number;
y: number;
};
```
## 7. 제네릭
```ts
function identity<T>(arg: T): T {
return arg;
}
identity<string>("hello");
identity<number>(123);
interface ApiResponse<T> {
data: T;
status: number;
}
```
## 8. 유틸리티 타입
```ts
interface User {
id: number;
name: string;
email: string;
}
type PartialUser = Partial<User>; // 모든 필드 옵셔널
type RequiredUser = Required<User>; // 모든 필드 필수
type PickUser = Pick<User, "id" | "name">; // 일부만
type OmitUser = Omit<User, "email">; // 일부 제외
```
## 9. 타입 가드
```ts
function isString(value: unknown): value is string {
return typeof value === "string";
}
function process(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase());
} else {
console.log(value.toFixed(2));
}
}
```
## 10. 클래스
```ts
class Animal {
constructor(public name: string) {}
speak(): void {
console.log(this.name + " makes a sound");
}
}
class Dog extends Animal {
constructor(name: string, public breed: string) {
super(name);
}
speak(): void {
console.log(this.name + " barks");
}
}
```