JS & TS/TypeScript

[TypeScript] Generic

Bay Im 2024. 2. 15. 09:19
  • 제네릭 함수
    • 호출하는 방식에 따라 다양한 타입으로 작동하도록 의도한다.
    • 함수의 기능이 똑같은데 매개변수의 타입과 반환하는 타입이 다를 때 제네릭 기법을 사용하여 한 개의 함수로 구현 가능
    • 제네릭 함수 구현
      • function 제네릭함수<T>(arg: T): T { return arg; }
        • 함수명 뒤에 <T>를 추가하고, T를 매개변수의 타입 또는 반환 타입으로 설정 가능
        • 꼭 <T>로 작성할 필요는 없고 다른 문자열도 사용 가능 (대부분 Type의 T로 작성)
    • 제네릭 함수 호출
      • <>안에 인수의 타입을 작성한다.
        • ex) let 변수1 = 제네릭함수<number>(123);
        • ex) let 변수2 = 제네릭함수<string>(’ABC’);
    • 다중 함수 타입 매개변수
      • 구현
        • function 다중제네릭함수<First, Second> (first: First, second: Second_ { return [first, second] as const; }
      • 호출
        • ex) const [name, age] = 다중제네릭함수(’Im’, 25);
        • ex) const [level, agree] = 다중제네릭함수<number, boolean>(10, true);
  • 제네릭 인터페이스
    • 인터페이스에서도 제네릭을 사용해 항목의 타입 정의 가능
      • // 구현
        interface 제네릭인터페이스<T> {
        	id: number,
        	name: string,
        	additional?: T;
        }
        
        // 호출
        type Color = 'red' | 'blue' | 'green';
        const info1: 제네릭인터페이스<Color> = {
            id: 1,
            name: 'lim',
            additional: 'red'
        };
        
        type Address = { sigungu: string, zipcode: string };
        const info2: Info<Address> = {
            id: 2,
            name: 'hong',
            additional: { sigungu: 'Seoul', zipcode: '04112'}
        }
  • 제네릭 인터페이스 구현
    • class 클래스<T> implements 제네릭인터페이스<T> { … }
  • 제네릭 클래스
    • 클래스도 제네릭 함수를 호출하는 것과 동일한 타입 인수 유추 규칙을 따른다.
      • // 구현 
        class Factory<T> {
        	protected products: T[];
        
        	constructor(product: T) {
        		this.products = [product];
        	}
        
        	create(product: T) {
        		this.products.push(product);
        	}
        
        	getProducts() {
        		return [...this.products];
        	}
        };
        
        // 호출
        const factory = new Factory({ name: 'KIA', description: 'car factory' });
        
        // 확장
        class CoffeeFactory<T> extends Factory<T> {}
        
        const coffeeFactory = new CoffeeFactory<{ menu: string, price: number }>({
            menu: 'americano',
            price: 2000
        });
  • 정적 클래스 제네릭
    • ex)
      • class BothLogger<OnInstance> {
            instanceLog(value: OnInstance) {
                console.log('instanceLog.value > ', value);
                return value;
            }
        
            static A: OnInstance;
            static staticLog<OnStatic>(value: OnStatic) {
                let instanceLogValue: OnInstance;
        
                console.log('staticLog.value > ', value);
                return value;
            }
        }
    • OnInstance 타입은 인스턴스 생성시 정해진다.
    • 인스턴스를 생성하지 않아도 접근 가능한 정적(static) 클래스 메서드에서는 클래스에 선언된 어떤 타입 매개변수에도 접근할 수 없다.
  • 메서드 제네릭
    • 인스턴스와 무관하게 메서드에서 자체 제네릭 타입 사용 가능
  • 제네릭 제한자
    • 제네릭 기본값
      • 함수 매개변수에 기본값을 제공하듯 제네릭 타입 매개변수에 기본 타입 지정 가능
    • 제한된 제네릭 타입 (extends)
      • extends 키워드를 사용해 T의 타입 제한
      • keyof는 전체 키 대상, extends keyof는 해당 프로퍼티의 특정키를 직접 검사
  • Promise
    • 최종적으로 resolve된 값을 나타내는 단일 타입 매개변수를 갖는다.
  • async 함수
    • async 함수의 반환 타입은 항상 Promise 타입이다.
  • 제네릭 명명규칙
    • 첫 번쨰 타입 인수로 T를 사용
    • 후속 타입 매개변수가 존재하면 U, V 등을 사용
    • 타입 인수가 어떻게 사용되어야 하는지 맥락과 관련된 정보가 알려진 경우 해당 용어의 첫 글자를 사용 (상태 관리 라이브러리-S, 키-K, 값-V)
    • 여러 개의 타입 매개변수를 갖거나 목적이 명확하지 않은 경우 완전한 이름을 사용
728x90

'JS & TS > TypeScript' 카테고리의 다른 글

[TypeScript] Utility Types  (0) 2024.02.15
[TypeScript] 선언 파일과 구성 및 옵션, 타입 운영  (0) 2024.02.15
[TypeScript] 타입 제한자  (0) 2024.02.15
[TypeScript] Class  (0) 2024.02.13
[TypeScript] Interface  (0) 2024.02.13