GENERIC

오픈소스·2022년 11월 29일
0
post-thumbnail
post-custom-banner

https://academy.dream-coding.com/courses/typescript

6.2 함수를 제네릭 하게 :)

function checkNotNull<T>(arg: T | null): T {
  if (arg == null) {
    throw new Error('not valid number!');
  }
  return arg;
}

const number = checkNotNull(123);

6.2 클래스를 제네릭 하게 :)

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 either: Either<number, number> = new SimpleEither<number, number>(4, 5);

6.3 제네릭 조건

function pay<T extends Employee>(employee: T): T {
  employee.pay();
  return employee;
}
function getValue(T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}
post-custom-banner

0개의 댓글