S E P H ' S

TypeScript 기초 연습 - 2 본문

Programing & Coding/TypeScript

TypeScript 기초 연습 - 2

yoseph0310 2020. 8. 30. 22:30

일반 객체를 interface로 타입 설정하기

interface Person {
    name: String;
    age?: number;
}

interface Developer {
    name: string;
    age?: number;
    skills: string[];
}

const person: Person = {
    name: '김사람',
    age: 20
};

const expert: Developer = {
    name: '김개발',
    skills: ['javascript', 'react']
};

  Person 인터페이스와 Developer 인터페이스가 형태가 유사한것을 볼 수 있다. 이럴때는 Developer 인터페이스에서 Person인터페이스를 extends 해서 상속받을 수 있다.

interface Person {
    name: String;
    age?: number;
}

interface Developer extends Person{
    skills: string[];
}

const person: Person = {
    name: '김사람',
    age: 20
};

const expert: Developer = {
    name: '김개발',
    skills: ['javascript', 'react']
};

const people: Person[] = [person, expert];

Type Alias 사용하기

  type은 특정 타입에 별칭을 붙이는 용도로 사용한다. 이를 사용하여 객체를 위한 타입을 설정할 수도 있고, 배열, 또는 그 어떤  타입이든 별칭을 붙여줄 수 있다.

type Person = {
    name: string;
    age?: number;
};

type Developer = Person & {
    skills: string[]
};

const person: Person = {
    name: '김사람'
};

const expert: Developer = {
    name: '김개발',
    skills: ['javascript','react']
};

type People = Person[];
const people: People = [person, expert];

type Color = 'red' | 'orange' | 'yellow';
const color: Color = 'red';
const colors: Color[] = ['red', 'orange'];

  type과 interface 둘 중 어느 것을 사용해도 무방하지만, 일관성 있게 사용하면 된다. 구버전의 타입스크립트에서는 type과 interface의 차이가 많이 존재했지만 현재는 큰 차이는 없다. 다만, 라이브러리를 작성하거나 다른 라이브러리를 위한 타입 지원 파일을 작성하게 될 때는 interface를 사용하는 것이 권장되고 있다.

Generics

 제네릭(Generics)은 타입스크립트에서 함수, 클래스, interface, type을 사용하게 될 때 여러 종류의 타입의 대하여 호환을 맞춰야 하는 상황에서 사용하는 문법이다.

 

함수에서 Generics 사용하기

 

  예를 들어, 우리가 객체 A와 객체 B를 합쳐주는 merge 라는 함수를 만든다고 가정해보자. 그런 상황에서는 A와 B가 어떤 타입이 올 지 모르기 때문에 이런 상황에서는 any라는 타입을 쓸 수도 있다.

function merge<A, B>(a: A, b: B): A & B {
    return {
      ...a,
      ...b
    };
}

const merged = merge({foo: 1},{bar: 1});

  제네릭을 사용할 때는 <T> 처럼 꺽쇠 안에 타입의 이름을 넣어서 사용하며, 이렇게 설정을 해주면 제네릭에 해당하는 타입에는 뭐든지 들어올 수 있게 되면서도, 사용할 때 타입이 깨지지 안헥 된다. 만약 함수에 이렇게 제네릭을 사용하게 된다면 함수의 파라미터로 넣은 실제 값의 타입을 활용하게 된다.

function wrap<T>(param: T) {
    return{
        param
    }
}

const wrapped = wrap(10);

  이렇게 함수에서 제너릭을 사용하면 파라미터로 다양한 타입을 넣을 수도 있고 타입 자원을 지켜낼 수 있다.

 

interface 에서 Generics 사용하기

interface Items<T> {
    list: T[];
}

const items: Items<string>={
    list: ['a','b','c']
};

  만약  Items<string> 타입을 사용하게 된다면, Items 타입을 지니고 있는 객체의 list 배열은 string[] 타입을 지니게 된다. 이렇게 함으로써, list가 숫자 배열인 경우, 문자열 배열인 경우, 객체배열, 또는 그 어떤 배열인 경우에도 하나의 interface만을 사용하여 타입을 설정할 수 있다.

 

Type alias 에서 Generics 사용하기

type Items<T> {
    list: T[];
}

const items: Items<string>={
    list: ['a','b','c']
};

 

클래스에서 Generics 사용하기

 

  Queue는 데이터를 등록할 수 있는 자료형이며, 먼저 등록(enqueue)한 항목을 먼저 뽑아올 수(dequeue) 있는 성질을 가지고 있다. 실생활에서 접할 수 있는 간단한 Queue 예시는 대기 줄이다. 대기 줄에서는 (누군가 새치기를 하지 않는 이상) 가장 먼저 온 사람이 먼저 들어간다. 이 로직이 바로 Queue이다.

class Queue<T> {
    list: T[] = [];
    get length() {
        return this.list.length;
    }
    enqueue(item: T){
        this.list.push(item);
    }
    dequeue(){
        return this.list.shift();
    }
}

const queue = new Queue<number>();
queue.enqueue(0);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
console.log(queue.dequeue());
console.log(queue.dequeue());
console.log(queue.dequeue());
console.log(queue.dequeue());
console.log(queue.dequeue());

  이 Queue 에서는 제너릭을 사용하여 다양한 원소 타입으로 이루어진 Queue의 타입을 설정할 수 있다.

  - ex) Queue<string> 이라고 하면 string 타입의 Queue가 되는 것이다.

'Programing & Coding > TypeScript' 카테고리의 다른 글

TypeScript 기초 연습  (0) 2020.08.29