
JavaScript의 한계
원래 브라우저 스크립트 언어로 시작, 간단한 코드 작성에 적합
Node.js 등장 후 서버 개발 등 브라우저 밖에서도 사용
대규모 프로젝트(수십만 줄)에서 오타·타입 불일치로 인한 버그 증가
1 < x < 3; // 항상 true
const area = obj.width * obj.heigth; // 오타
TypeScript의 등장
tsc에서 타입 제거) 코드 안전성을 향상타입 추론: 값에서 타입 자동 결정
let name = "Lee"; // string 추론
타입 정의: interface와 type
extends
interface Animal { name: string; }
interface Dog extends Animal { breed: string; }
implements
interface Printable { print(): void; }
class Document implements Printable {
print() { console.log("printing..."); }
}
인터섹션(&)
type A = { a: string };
type B = { b: number };
type C = A & B; // { a: string; b: number }
유니언(|)
type LockState = "locked" | "unlocked";
Generics
interface Backpack<T> {
add: (obj: T) => void;
get: () => T;
}
조건부 타입
type IsString<T> = T extends string ? "yes" : "no";
템플릿 리터럴 타입
type EventName = `on${Capitalize<string>}`;
인덱스드 타입
interface Person { name: string; age: number; }
type NameType = Person["name"]; // string
키 리매핑
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
};
infer
type Return<T> = T extends (...args: any) => infer R ? R : never;
| 유틸리티 | 설명 |
|---|---|
Partial<T> | 모든 프로퍼티 선택적 |
Required<T> | 모든 프로퍼티 필수 |
Pick<T, K> | 특정 키만 선택 |
Omit<T, K> | 특정 키 제외 |
Readonly<T> | 수정 불가 |
Record<K, T> | 키-값 타입 매핑 |
Exclude<T, U> | U 제외 |
Extract<T, U> | U만 추출 |
NonNullable<T> | null/undefined 제거 |
타입 가드
function isString(v: unknown): v is string {
return typeof v === 'string';
}
as const
const COLORS = ["red", "green"] as const;
never 타입으로 모든 경우 처리 체크
function check(x: string | number) {
if (typeof x === "string") {}
else if (typeof x === "number") {}
else {
const _exhaustive: never = x;
}
}
| 옵션 | 설명 | 기본값 |
|---|---|---|
strict | 모든 엄격 모드 활성화 | false |
noImplicitAny | any 추론 차단 | false |
strictNullChecks | null/undefined 엄격 체크 | false |
exactOptionalPropertyTypes | 옵셔널과 undefined 구분 | false |
esModuleInterop | CommonJS 모듈을 ES import로 | false |
resolveJsonModule | JSON import 가능 | false |
참고 링크(https://www.typescriptlang.org/ko/docs/handbook/intro.html)