Santos의 개발블로그

TypeScript - Generic 본문

Language & Framework & Library/TypeScript

TypeScript - Generic

Santos 2021. 2. 9. 09:00

* 이 글은 드림코딩 by 엘리님 강의를 참고하여 만들었습니다

😡 = 지양해야하는 코드 

😍 = 지향해야하는 코드

 

1. Function

{
    // 😡
    function checkNotNullBad(arg: number | null): number {
        if (arg == null) {
            throw new Error("not valid number!");
        }
        return arg;
    }

    //😡
    function checkNotNullAnyBad(arg: any | null): any {
        if (arg == null) {
            throw new Error("not valid number!");
        }
        return arg;
    }
    
   //😍
    function checkNotNull<T>(arg: T | null): T {
        if (arg == null) {
            throw new Error("not valid number!");
        }
        return arg;
    }

    const number = checkNotNull(123);
    const boal: boolean = checkNotNull(true);
}

2. Class

// either: a or b
interface Either<L, R> {
    left: () => L;
    right: () => R;
}

class SimpleEither<L, R> implements Either<L, R> {
    constructor(private leftValue: L, private rightValue: R) {}
    left(): L {
        return this.leftValue;
    }
    right(): R {
        return this.rightValue;
    }
}

const best = new SimpleEither({ name: "santos" }, "hello");

3. Constraint

interface Employee {
    pay(): void;
}

class FullTimeEmployee implements Employee {
    pay() {
        console.log(`full time!!`);
    }

    workPullTime() {}
}

class PartTimeEmployee implements Employee {
    pay() {
        console.log(`full time!!`);
    }

    workPartTime() {}
}

// 세부적인 타입을 인자로 받아서 정말 추상적인 타입으로 다시 리턴하는 함수는 😡
function payBad(employee: Employee): Employee {
    employee.pay();
    return employee;
}

// 제네릭을 사용해 더욱 추상적인 타입으로 변경 😍
function payGood<T extends Employee>(employee: T): T {
    employee.pay();
    return employee;
}

const santos = new FullTimeEmployee();
const mario = new PartTimeEmployee();

const santosAfterPayBad = payBad(santos);
const marioAfterPayBad = payBad(mario);

const santosAfterPay = payGood(santos);
const marioAfterPay = payGood(mario);

santosAfterPayBad.pay(); // Empoyee의 타입을 리턴하기 때문에 pay밖에 호출이 안되는 문제 발생 😡
santosAfterPay.workPullTime(); // 타입이 변경되어 기존 Class 내에 있는 함수 리턴 가능함 😍

// -------------------------------------------------------------------------------

const obj = {
    name: "santos",
    age: 20,
};

const obj2 = {
    animal: "dog",
};

function getValue<T, K extends keyof T>(obj: T, key: K): T[K] {
    return obj[key];
}

console.log(getValue(obj, "name")); // santos
console.log(getValue(obj, "age")); // 20
console.log(getValue(obj2, "animal")); // dog

< 참고자료 >

 

[사이트] #드림코딩 by 엘리

academy.dream-coding.com/

 

<TypeScript> Assertion end

'Language & Framework & Library > TypeScript' 카테고리의 다른 글

TypeScript - OOP  (0) 2021.02.08
TypeScript - Basic Syntax(기본 문법)  (0) 2020.07.04
Comments