카테고리 없음

타입스크립트 stack <generic> ver

hojung 2021. 7. 29.
728x90
반응형
{
    interface Stack<T>{ // generic 선언은 interface, type, class 의 선언부에 행한다. 

        readonly size: number;
        push(value : T) : void;
        pop() : T;
    }

    type StackNode<T> = {
        readonly value : T;
        readonly next?: StackNode<T>;
    }
    class StackImpl<T> implements Stack<T>{
        private _size : number = 0;
        private head? : StackNode<T>; 
        get size()
        {
            return this._size;
        }
        push(value : T )
        {
            const node : StackNode<T> = {value,next: this.head};
            this.head = node;
            this._size++;
        }   

        pop() : T{ //null == undefined 값 확인 , null !== undefined 엄격한 타입 체크
            if(this.head == null)
            {
                throw new Error ('Stack is empty');
            }
            const node = this.head;
            this.head = node.next;
            this._size--;
            return node.value;
        }
    }

    const stack = new StackImpl<string>();
    stack.push('jeongho');
    stack.push('yoon hak');
    stack.push('minyeong');
    stack.push('daeun');

    const stack2 = new StackImpl<number>();
    stack2.push(1);
    stack2.push(2);
    stack2.push(3);
    stack2.push(4);
    while(stack.size !== 0)
    {
        console.log(stack.pop());
    }

    while(stack2.size !== 0)
    {
        console.log(stack2.pop());
    }
}

 

generic을 이용해서 모든 타입을 받을 수 있는 stack을 만들어 보았다. generic은 c++의 템플릿과 비슷한 개념으로 타입에 상관없이 어떠한 객체나 클래스, 함수를 만들고 싶을 때 이용된다. 이용하는 방법은

각각의 interface나 class이름 혹은 함수 이름 옆에 <> 안에 타입 이름으로 사용할 키워드를 지정해주면 되는데 대게 T나 다른 알파벳 대문자를 많이 이용한다.  

 

각각의 선언부에 generic을 선언하면 다음과 같이 그 선언한 T나 다른 알파벳 대문자를 그 scope안에서 이용할 수 있게 되는데 거의 대부분의 api문서들의 경우 generic을 사용해서 코드를 작성한 것이 대부분이므로 generic을 모른다면 api문서들을 이해하는데 어려움을 겪을 수도 있다.

 

위의 코드를 실행시켜보면 다음과 같은 결과가 나오게 된다.

결과 화면

728x90
반응형

댓글