레슨 6 / 8·20분
클래스와 모듈
TypeScript 클래스
TypeScript는 JavaScript 클래스에 접근 제어자(public, private, protected), 추상 클래스, 인터페이스 구현 등을 추가합니다.
typescript
class User {
// 접근 제어자
public name: string;
private password: string;
protected role: string;
readonly id: number;
// 생성자 단축 문법
constructor(
public email: string,
name: string,
password: string,
) {
this.id = Date.now();
this.name = name;
this.password = password;
this.role = "user";
}
// 메서드
changePassword(newPw: string): void {
this.password = newPw;
}
// getter
get displayName(): string {
return this.name + " (" + this.email + ")";
}
}
// 추상 클래스 — 직접 인스턴스 생성 불가
abstract class Shape {
abstract area(): number;
describe(): string {
return "넓이: " + this.area();
}
}
class Circle extends Shape {
constructor(public radius: number) { super(); }
area(): number { return Math.PI * this.radius ** 2; }
}인터페이스 구현 (implements)
typescript
// 인터페이스를 구현하는 클래스
interface Serializable {
toJSON(): string;
}
interface Printable {
print(): void;
}
class Document implements Serializable, Printable {
constructor(
public title: string,
public content: string,
) {}
toJSON(): string {
return JSON.stringify({ title: this.title, content: this.content });
}
print(): void {
console.log("=== " + this.title + " ===");
console.log(this.content);
}
}tsconfig.json 핵심 옵션
json
{
"compilerOptions": {
// 타입 체크 강도
"strict": true, // 모든 strict 옵션 활성화
"noImplicitAny": true, // 암시적 any 금지
"strictNullChecks": true, // null/undefined 엄격 체크
// 모듈 & 빌드
"target": "ES2022", // 출력 JS 버전
"module": "ESNext", // 모듈 시스템
"moduleResolution": "bundler", // 번들러 방식 모듈 해석
"esModuleInterop": true, // CommonJS 호환
"resolveJsonModule": true, // JSON import 허용
// 경로 & 출력
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"] // 경로 별칭
},
"outDir": "./dist",
// 기타
"declaration": true, // .d.ts 생성
"sourceMap": true, // 소스맵 생성
"skipLibCheck": true // node_modules 타입 체크 건너뛰기
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}💡
strict: true는 TypeScript의 모든 strict 옵션을 한번에 켭니다. 새 프로젝트에서는 항상 strict 모드를 사용하는 것을 권장합니다.