TypeScript

[TypeScript] generic(제네릭)

wwxs 2024. 8. 23. 17:49

generic(제네릭)

  • 재사용 가능한 컴포넌트(코드 단위)를 만드는데 사용
  • 해당 컴포넌트가 처리할 데이터 타입을 미리 지정하지 않고, 해당 컴포넌트를 사용하는 시점에서 원하는 데이터 타입 지

제네릭 필요성

  • 코드의 중복을 줄임
  • 재사용 가능한 컴포넌트를 생성
  • 타입 안정성 보장 → '컴파일' 시점에서 타입을 체크 ('런타임' 환경에서 발생할 수 있는 에러를 방지)

제네릭 기본 문법

  • 사용할 컴포넌트(변수, 함수, 클래스 등)의 이름 뒤에 꺽쇠괄호(<>) 안에 타입 변수를 지정
  • 함수나 클래스 등을 사용할 때 활용할 타입을 명시
더보기
더보기
function generic<T>(arg: T): T { // 함수 정의 시 타입 변수 지정
  // 타입 변수 T (단일 타입 변수)
  return arg;
}
generic<string>('안녕하세요'); // 함수 호출 시 타입 변수에 활용할 타입을 명시
generic<number>(123);
generic<boolean>(true);

 

1. 제네릭 함수

더보기
더보기
function genericFunc<T>(args: T[]): T[] { // string[], number[]
  console.log(`배열의 길이: ${args.length}`);
  return args;
}

let resultFunc = genericFunc<boolean>([true, false, false]);
console.log(`함수의 반환값: ${resultFunc}`);

 

2. 제네릭 인터페이스

더보기
더보기
interface IGeneric<T> {
  (key: T): T,  // 인터페이스 내부의 속성 타입을 명시
}


function example<T>(arg: T): T {
  return arg;
}

let myGeneric: IGeneric<number> = example;
console.log(example(5));
console.log(myGeneric(5));

 

3. 제네릭 클래스

더보기
더보기
class GenericClass<T> {
  value: T;
  add: (x: T, y: T) => T; // 해당 클래스로 인스턴스화 될 때 인자로 함수를 전달받음

  constructor(value: T, addFunc: (x: T, y: T) => T) { 
    this.value = value;
    this.add = addFunc;
  }
}

class basicClass {
  value: string;

  constructor(value: string, addFunc: (x:string, y:string) => string) {
    this.value = value;
    this.add = addFunc;
  }

  add: (x: string, y: string) => string;
}

let myGenericNumber = new GenericClass<number>(0, function(x, y) {return x + y})
console.log(myGenericNumber.add(4, 5)); // 9

let myGenericString = new GenericClass<string>('', function(x, y) {return `${x}${y}`})
console.log(myGenericString.add('홍', '동현')); // 홍동현

 

제네릭의 제약 조건

  • 타입 매개변수가 특정 조건을 만족해야 한다는 것을 명시하는 방법
  • 제네릭 타입의 사용 범위를 제한

 

'TypeScript' 카테고리의 다른 글

[TypeScript] 인터페이스  (0) 2024.08.20
[TypeScript] 타입  (0) 2024.08.19
[TypeScript] 기본 문법  (0) 2024.08.19
[TypeScript] 환경설정  (0) 2024.08.19
[TypeScript] 타입스크립트  (0) 2024.08.19