하위 태스크 1 ~ 2

인터페이스 정의

interface 키워드로 타입 정의

선택적/readonly 프로퍼티

인터페이스에서 ?와 readonly 사용

src/interfaces.ts:

interface Person {
    name: string;
    age: number;
    job?: string;
    readonly administrator: boolean;
}

하위 태스크 3

인터페이스 확장

extends로 인터페이스 상속

src/interfaces.ts:

interface Animal {
    species: string;
    name: string;
    height: number;
}
 
interface Dog extends Animal {
    hungry: boolean;
}
 
interface Cat extends Animal {
    bored: boolean;
}

하위 태스크 4

인터페이스 선언 합치기

같은 이름 인터페이스 병합 확인

선언 병합에 의해 Animal 클래스는 species, name, height 속성을 가져야 한다. 다음 코드 블록에서 animal 객체는 height 속성이 없어 에러를 발생시킨다.

src/interfaces.ts:

// ...
 
interface Animal {
    height: number;
}
 
// Property 'height' is missing in type '{ species: string; name: string; }' but required in type 'Animal'. 
 
// const animal: Animal = {
//     species: "mammal",
//     name: "Zin",
// };

하위 태스크 5

클래스 필드 타입

필드에 타입 주석 추가

src/classes.ts:

class Employee {
    name: string;
    age: number;
} 

하위 태스크 6

생성자 함수

constructor에서 필드 초기화

src/classes.ts:

class Employee {
    name: string;
    age: number;
 
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
} 

하위 태스크 7

선택적 필드

클래스에서 선택적 필드 사용

src/classes.ts:

class Employee {
    name: string;
    age: number;
    position?: string;
 
    constructor(name: string, age: number, position?: string) {
        this.name = name;
        this.age = age;
        this.position = position;
    }
} 
 
const employee = new Employee("홍길동", 24, "programmer");

하위 태스크 8

인터페이스 구현

implements로 인터페이스 구현

src/interface-implementation.ts:

interface CharacterInterface {
    name: string;
    job: string;
    forward(n: number): void;
}
 
class Character implements CharacterInterface {
    name: string;
    job: string;
 
    constructor(name: string, job: string) {
        this.name = name;
        this.job = job;
    }
 
    forward(n: number) {
        console.log(`${n}칸 전진`);
    }
}

하위 태스크 9 ~ 11

public 접근 제어자

모든 범위에서 접근 가능 확인

private 접근 제어자

클래스 내부에서만 접근 확인

protected 접근 제어자

파생 클래스에서 접근 확인

src/access-modifiers.ts:

class Employee {
    public static lastId = 0;
 
    private id: number;
    protected name: string;
    protected organization: string;
 
    constructor (name: string, organization: string) {
        this.id = Employee.lastId += 1;
        this.name = name;
        this.organization = organization;
    }
 
    public introduce() {
        console.log(`안녕하세요. ${this.organization} 소속 ${this.id}번 사원 ${this.name}입니다.`);
    }
}
 
class Administrator extends Employee {
    public grant(task: string) {
        console.log(`${this.organization} 부서장 ${this.name}의 권한으로 ${task} 수행을 승인합니다.`);
    }
}
 
const employee = new Employee("홍길동", "무선사업");
employee.introduce(); // 안녕하세요. 무선사업 소속 1번 사원 홍길동입니다.
 
const administrator = new Administrator("김철수", "보안감사");
administrator.grant("감사 업무"); // 보안감사 부서장 김철수의 권한으로 감사 업무 수행을 승인합니다.