상똥이의 Back-End 공부방

[TypeScript] 제네릭 본문

TypeScript

[TypeScript] 제네릭

상똥백 2024. 9. 3. 19:25

 

1. 제네릭

- 타입을 파라미터 변수로 받는 방식

 

2. 제네릭의 장점

- 타입의 구분 없이 사용할 수 있어 활용도가 높아짐

- 타입에 따라 동일한 로직을 여러번 작성할 필요가 없어지므로 코드의 중복을 제거할 수 있음

 

3. 제네릭 vs 유니온

- 유니온 타입(Ex. string | number) 또는 any를 사용하면 인자값은 해결되지만

- 반환값에 대한 기능이 제한됨

유니온 제네릭

 

4. 인터페이스에 활용

interface Example<T> {
    value: T;
    selected: boolean;
}

const obj: Example<string> = {value: 'text', selected: false};

 

 

5. 제네릭의 타입 제한

- 배열로 활용하기

function logTextLength<T>(text: T[]): T[] {
    text.forEach(
        function(text) {
            console.log(text)
        }
    )
    return text;
}

logTextLength<string>(['a', 'b', 'c']);

- 정의된 타입 이용하기

interface lengthType {
    length: number;
}

function logTextLength<T extends LengthType>(text: T): T{
    text.length;
    return text;
}

- keyof 사용하기

interface ShoppingItem {
    name: string;
    price: number;
    stock: number;
}

function getShoppingItemOption<T extends keyof ShoppingItem>(itemOption: T): T {
    return itemOption;
}

getShoppingItemOption('name');
getShoppingItemOption('price');
getShoppingItemOption('stock');

 

'TypeScript' 카테고리의 다른 글

[TypeScript] 클래스  (1) 2024.09.03
[TypeScript] 인터페이스와 타입  (0) 2024.09.02
[TypeScript] 데이터 타입  (0) 2024.09.02
[TypeScript] 타입스크립트 개요  (0) 2024.09.01