Generic Classes

kukudas·2022년 2월 9일
0

TypeScript

목록 보기
33/39

Introduction to TypeScript generic classes

제네릭 클래스는 제네릭 타입 parameter list를 <>안에 가지고 있음.

class className<T>{
    //... 
}

타입스크립트는 아래처럼 여러개의 제네릭 타입을 타입 parameter list에 가질 수 있게해줌.

class className<K,T>{
    //...
}

제네릭 constraints는 클래스의 제네릭 타입에도 사용가능함.

class className<T extends TypeA>{
    //...
}

type parameter를 클래스에 사용하는거는 메소드와 property가 같은 타입으로 동작하게해줌.

TypeScript generic classes example

아래는 제네릭 스택 클래스인 Stack<T>를 만들었음.

class Stack<T> {
    private elements: T[] = [];

    constructor(private size: number) {
    }
    isEmpty(): boolean {
        return this.elements.length === 0;
    }
    isFull(): boolean {
        return this.elements.length === this.size;
    }
    push(element: T): void {
        if (this.elements.length === this.size) {
            throw new Error('The stack is overflow!');
        }
        this.elements.push(element);

    }
    pop(): T {
        if (this.elements.length == 0) {
            throw new Error('The stack is empty!');
        }
      	// 여기서 !써가지고 undefined 타입을 제거해줘야함.
        return this.elements.pop()!;
    }
}

아래 줄로 number로 된 스택 생성함

let numbers = new Stack<number>(5);

아래 함수는 low와 high 사이의 랜덤한 숫자를 리턴해줌.

function randBetween(low: number, high: number): number {
    return Math.floor(Math.random() * (high - low + 1) + low);
}

이제 randBetween() 함수를 이용해서 랜덤한 numbernumbers 스택 안에 넣어줄 수 있음.

let numbers = new Stack<number>(5);

while (!numbers.isFull()) {
  	let n = randBetween(1, 10);
    console.log(`Push ${n} into the stack.`)
    numbers.push(n);
}

// Output:
Push 3 into the stack.
Push 2 into the stack. 
Push 1 into the stack. 
Push 8 into the stack. 
Push 9 into the stack. 

아래는 스택이 빌때까지 element를 pop 하는걸 보여줌.

while (!numbers.isEmpty()) {
    let n = numbers.pop();
    console.log(`Pop ${n} from the stack.`);
}

// Output:
Pop 9 from the stack.
Pop 8 from the stack.
Pop 1 from the stack.
Pop 2 from the stack.
Pop 3 from the stack.

비슷하게 string의 스택을 만들 수도 있음.

let words = 'The quick brown fox jumps over the lazy dog'.split(' ');

let wordStack = new Stack<string>(words.length);

// push words into the stack
words.forEach(word => wordStack.push(word));

// pop words from the stack
while (!wordStack.isEmpty()) {
    console.log(wordStack.pop());
}

위는 다음과 같이 동작함.

  • 먼저 문장을 단어로 나눔.
  • 두번째로, 단어 개수만큼의 스택을 생성함.
  • 세번째로, word 배열의 단어들을 스택에 집어 넣음.
  • 마지막으로 스택이 빌떄까지 단어들을 뺌.

출처

0개의 댓글

관련 채용 정보