Generic

Jung taeWoong·2021년 5월 5일
0

typescript

목록 보기
4/11
post-thumbnail

Generic 제네릭이란..?

  • 어떤 타입이든 받을 수 있고 코딩을 할 때 타입이 결정된다. (타입 보장 O)
  • 사용자가 어떤 타입인지 정할수 있다.
  • 보통 제네릭은 타입을 대문자 하나로 사용 ex: <T>

Generic 장점

  • 유연하다.
  • 타입 보장이 좋다.
  • 재사용성을 높일 수 있다.
  • 활용성이 높은 클래스, 함수를 만들 수 있다.

제네릭 함수 예제

function checkNotNull<T> (arg: T | null): T {
  if (arg == null) {
    throw new Error('not valid number');
  }
  return arg;
}
const num = checkNotNull(50); // 코드를 작성할 때 타입이 정해짐
const boal = checkNotNull(true);

제네릭 클래스 예제

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: 'woong'}, 'hello');

제네릭 조건

  • 제네릭은 어떤 타입이든 들어올 수 있기 때문에 코딩하는 시점에는 타입에 대한 정보가 없다.
  • 조건을 걸어둠으로써 조금 더 제한적인 범위 내에 일반화된 제네릭을 이용 가능
  • <T extends XX>
const obj = {
  name: 'woong',
  age: 27,
}
// keyof XX: 어떤 오브젝트 안에 들어있는 key의 타입
function getValue<T, K extends keyof T> (obj: T, key: K): T[K] {
  return obj[key];
}
profile
Front-End 😲

0개의 댓글