본문 바로가기
프로그래밍/타입스크립트

타입스크립트 - 제네릭 클래스

by Programmer.Junny 2025. 2. 15.
class GenericList<T> {
    constructor(private list: T[]) {}

    push(data: T) {
        this.list.push(data);
    }

    pop() {
        this.list.pop();
    }

    print() {
        console.log(this.list);
    }
}

클래스도 제네릭으로 지정할 수 있다.

매개변수의 타입을 다양한 타입을 받아야한다면 위와 같이 지정할 수 있다.

const numberList = new GenericList([1, 2, 3]);
numberList.pop();
numberList.push(4);
numberList.print();

const stringList = new GenericList(['hi', 'hello', 'good']);
stringList.pop();
stringList.push('bye');
stringList.print();

최근댓글

최근글

skin by © 2024 ttuttak