teklog

TypeScript 입문하기 5 - Generic

2022/09/05

n°6

category : TypeScript

// migrated from old blog


Generics

: 요청에 따라 call signature를 생성하는 방법 .

💡 Generic은 Placeholder<> 와 함께 사용된다.




type Generic = {
  <T>(a: T[]) : T
}

// alias Generic은 T타입이 들어있는 배열을 매개변수로 받고, T 타입의 데이터를 반환한다.

const GenericFunc : Generic = (a) =>  {
  return a[0]
}

GenericFunc([1,2,3,4,'asd',123,'123'])
GenericFunc([true,false,3,4,'asd',123,'123'])

generic을 이용해 함수의 매개변수를 늘릴 때



type Generic = <T, V>(a:T[], b: V) => T

const GenericFunc : Generic = (a) =>  {
  return a[0]
}

// 에러, Generic에서 매개변수를 2개로 받기로 지정했기 때문에
// GenericFunc([1,2,3,4,'asd',123,'123'])
GenericFunc([1,2,3,4,'asd',123,'123'], "fixed")

const A = GenericFunc([true,false,3,4,'asd',123,'123'], false)

// 컴파일 에러, 첫번째 인자 배열의 첫번째 요소가 boolean 타입이기 때문에 컴파일에러 발생
A.toUpperCase();

더 자주 사용되는 Generic 사용 방법



const GenericFunc<T> = (a:T[]) => {
return a[0]
}

Generic([1,2,3,4])
Generic([true,2,null,'string'])

type Player<E> = {
name: string
extra : E
}

type NicoPlayer = Player<{favFood : string}>

하나의 객체에서 한 key의 데이터 타입만 계속 변한다면



type Player<E> = {
name : string
skill : E
}

const PlayerOne : Player<Array<string>> = {
name : 'me',
skill : ['JS', 'TS', 'Spring']
}

const PlayerTwo : Player<{main : string, sub : string, count : number}> = {
name : 'me',
skill : {main: 'NextJS', sub:'TypeScript', count: 32}
}

앨리어스, 인터페이스 선언 없이 함수에 제네릭 적용하기



function GenericFunc<T> (a: T) : T {
return a
}

TypeFunc<number>(1); 
// 1 반환

TypeFunc<string>('a')
// a 반환

화살표 함수에 바로 제네릭 적용하기



const GenericArrow = <T extends {}> (a : T) => {
return a
}

TypeFunc<number>(1); 
// 1 반환

TypeFunc<string>('a')
// a 반환