typescript interface 중 - 2

Interfaces

TypeScript Interface 설명

목차

  1. Introduction

  2. Optional properties

  3. Readonly properties

  4. Excess preperty checks

  5. Function types

  6. Indexable types

  7. Class Types


  1. Extending interfaces

  2. Hybrid Types

  3. Interfaces extending Classes

Class Types

Implementing an interface

가장 평범한 형태의 iface(interface) 사용은 class가 어떤 특정한 형태를 유지하게 만드는 것이며 이것은 ts에서 가능하다.

interface ClockInterface {
    currentTime: Date;
}

class Clock implements ClockInterface {
    currentTime: Date;
    constructor(h: number, m: number);
}

또한 메서드를 interface에 선언하고 implements 된 class가 구현하게 강제할 수 있다. 아래의 예제를 보자

interface ClockInterface {
    currentTime: Date;
    setTime(d: Date): void;
}

class Clock implements ClockInterface {
    currentTime: Date;
    setTime(d: Date) {
        this.currentTime = d;
    }

    constructor(h: number, m: number) {}
}

iface는 public과 private사이드 모두를 구현하기보다는 public사이드를 구현한다. 덕분에 클래스에서 private side가 있는지 아닌지 확인하는 것을 막는다.

Difference between the static and instance sides of classes

클래스와 iface를 다룰 때, class가 두가지 성질을 가지고 있다는 점을 마음에 두고 있다면 도움이 될 것이다. 첫번째는 static side이고 하나는 instance side이다. 당신은 아마 이미 눈치 채고 있을 것이다. constructor의 형태를 정의한 iface를 implements한 클래스는 error를 발생시킨다는 것을. 왜냐하면 implements 했을 때 interface가 체크하는 것은 오로지 instance사이드의 요소들을 체크할 뿐 static 사이드는 검사하지 않기 때문이다.(constructor는 static 사이드에 있다.)

interface ClockConstructor {
    new (hour: number, minute: number): Object;
}

class Clock implements ClockConstructor { // error
    currentTime: Date;
    constructor(h: number, m: number) {}
}

대신에, class의 static 사이드를 직접 건드려야 할것이다. 아래의 example에서는 우리는 두개의 iface를 정의했는데, 하나는 ClockConstructor이고(이름과 동일하게 constructor를 정의하였다.) 나머지 하나는 ClockInterface이며 instance 사이드를 규정할 것이다. 다음 편의를 위해 createClock이라는 함수를 정의하였으며, 이 함수는 인자로 넣은 클래스의 instance를 반환한다.

interface ClockConstructor {
    new (hour: number, minute: number): ClockInterface;
}

interface ClockInterface {
    tick(): void;
}

function createClock(ctor: ClockConstrucgtor, hour: number, minute: number) : ClockInterface
{
    return new ctor(hour, minute);
}

class DigitalClock implements ClockInterface {
    constructor(h: number, m: number) {}
    tick() {
        console.log('beep beep');
    }
}

class AnalogClock implements ClockInterface {
    constructor(h: number, m: number) {}
    tick() {
        console.log('tick tock');
    }
}

let digital = createClock(DigitalClock, 12, 17);
let analog = createClock(AnalogClock, 7, 32);

createClock의 첫번째 인자값으로 생성자의 형태를 체크한다. 위의 예제에서는 createClock(AnalogClock, 7, 32) 에서 AnalogClock의 성성자가 ClockConstructor iface의 생성자 형태와 맞는지 체크한다.

Extending Interfaces

Hybrid Types

Interfaces Extending Classes

1개의 좋아요