Typescript 스터디

Typescript의 고급 타입, 제네릭, 데코레이터를 활용하는 방법을 자세히 알아봅니다.

고급 타입

Intersection

인터섹션 타입은 interface 간 상속 extends 와 같은 효과를 내게 된다.

type ElevatedEmployee = Admin & Employee;

Type Guard

특정 타입을 확정할 수 있게 만들어주는 역할을 한다.

function add(a: string | number, b: string| number) {
    if(typeof a === "string" || typeof b === "string") {
        return a.toString() + b.toString();
    }
    return a+b;
}

class Car() {}
class Truck () {
    constructor(readonly loadCargo: boolean) {}
}
type Vehicle = Car | Truck;

function useVehicle(vehicle: Vehicle) {
    if("loadCargo" in vehicle) {

    }
    if(vehicle instanceof Car) {

    }
}

Discriminated Unions

interface Bird {
    type: "bird",
    flyingSpeed: number;
}
interface Horse {
    type: "horse",
}
type Animal = Bird | Horse;

function moveAnimal(animal: Animal) {
    switch(animal.type) {
        case "bird":
            console.log("bird");
            console.log(bird.flyingSpeed);
        case "horse":
            console.log("h orse");
    }
}

Index Type

key, value 가 string 인 객체 타입을 정의하고 싶을 때 다음과 같이 지정할 수 있다.

interface ErrorContainer {
    [prop: string]: string
}

Overloading

function add(a: number, b: number): number
function add(a: string, b: string): string
function add(a: number, b: string): string
function add(a: string, b: number): string
function add(a: string | number, b: string | number): string | number {
    return a + b;
}

Optional Chaining

const fetchedUserData = {
    id: "u1",
    name: "Heejae",
    // job: {title: "CEO"}
}
console.log(fetchedUserData.job?.title);




Generics

Function Generics

function merge<T extends object, U extends object>(objA: T, objB: U): T & U {
  return Object.assign(objA, objB);
}

const a = {
  name: "a",
}
const b = {
  description: "b",
}
const ab = merge(a, b);
function extractAndConvert<T extends object ,U extends keyof T>(obj: T, key: U) {
    return `Value : ${obj[key]}`
}

Class Generics

Generics 를 이용해서 Class 도 만들어낼 수 있다.

class Storage<T> {
    private data = T[];

    addItem(item: T) {
        this.data.push(item);
    }
    removeItem(item: T) {
        this.data.splice(this.data.indexOf(item), 1);
    }
}

Decorators

@ 는 타입스크립트에서 특별한 예약어이다. @ 뒤에는 항상 함수를 지목해야 한다. 실행하는 것이 아니고, 지목해야 한다. 선언부에서 Decorator 내부의 함수가 실행되는 순서는 Top-Down 이고, 실제로 함수가 실행되는 순서는 Bottom-Top 순서이다.

목차

고급 타입 Type Guard Discriminated Unions Index Type Overloading Optional Chaining Generics Function Generics Class Generics Decorators

이것도 읽어보세요