Generic Interfaces

kukudas·2022년 2월 9일
0

TypeScript

목록 보기
32/39

Introduction to TypeScript generic interfaces

클래스와 비슷하게 인터페이스도 제네릭하게 할 수 있음. 제네릭 인터페이스는<>안에 제네릭 타입 parameter list를 가지고 있음.

interface interfaceName<T> {
    // ...
}

위는 type parameter T가 인터페이스의 모든 멤버한테 보이게 만들어줌.

이 type parameter list는 아래처럼 하나 이상의 타입을 가질 수있음.

interface interfaceName<U,V> {
    // ...
}

TypeScript generic interface examples

1) Generic interfaces that describe object properties

아래는 2개의 멤버인 key와 value를 각각 K, V로 가진 제네릭 인터페이스임.

interface Pair<K, V> {
    key: K;
    value: V;
}

let month: Pair<string, number> = {
    key: 'Jan',
    value: 1
};

console.log(month);

// Output:
{ key: 'Jan', value: 1 }

이제 Pair 인터페이스를 이용해서 key/value 쌍을 어떤 타입으로던지 사용할 수 있음. 위 에서는 month 각각 string과 number인 key-value 쌍을 만들었음.

2) Generic interfaces that describe methods

아래는 제네릭 인터페이스로 2개의 메소드를 선언한 코드임.
List<T> 제네릭 클래스는 Colletionc<T> 인터페이스를 적용했음.

interface Collection<T> {
    add(o: T): void;
    remove(o: T): void;
}

class List<T> implements Collection<T>{
    private items: T[] = [];

    add(o: T): void {
        this.items.push(o);
    }
    remove(o: T): void {
        let index = this.items.indexOf(o);
        if (index > -1) {
            this.items.splice(index, 1);
        }
    }
}

List<T> 클래스로 여러 타입의 list를 만들어 낼 수 있음.
아래는 위 제네릭 클래스를 이용한 예시임.

let list = new List<number>();

for (let i = 0; i < 10; i++) {
    list.add(i);
}

3) Generic interfaces that describe index types

아래는 인덱스 타입을 나타낸 인터페이스임.

interface Options<T> {
  	// 여기서  [name: string]: T는 앞에 키인 name이 string타입이고 여러개인데 value가 T타입이라는 거임.
    [name: string]: T
}

let inputOptions: Options<boolean> = {
    'disabled': false,
    'visible': true
};

출처

0개의 댓글

관련 채용 정보