타입 스크립트의 Generic

Seong·2022년 11월 9일
0

Type_Script

목록 보기
3/7

Generic

Generic

간단하게 말하면 TypePlaceholder

선언 시점이 아니라 생성 시점에 타입을 명시하여 하나의 타입만이 아닌 다양한 타입을 사용할 수 있도록 하는 기법

타입스크립트에선 호출할때 따로 지정하지 않은경우 저절로 Generic 타입을 추론함

type Print = {
  <T>(arr: T[]): T  //Generic 지정
}

const superPrint: Print = (arr) => arr[0]
const a =superPrint([1])    //number
const b =superPrint(['21', '222', '333',false]); //string
const c = superPrint([true,false,22,'하이']) //boolean

const d = superPrint<string>(['하이']);  //타입추론을 사용하지않고 타입을 직접 지정,

복수의 Generic 설정도 가능하다

type Print = {
  <T, K>(arr: T[], second: K): T
}

const superPrint: Print = (arr, second) => {
  console.log(typeof arr[0]);
  console.log(typeof second);
  return arr[0]
}
const a = superPrint([1], 2)
const b = superPrint(['21', '222', '333', false], true);
const c = superPrint([true, false, 22, '하이'], '문자열')

const d = superPrint<string, number>(['하이'], 23);  //타입추론을 사용하지않고 타입을 직접 지정

타입을 재사용하는 데에도 사용 가능

type Player2<T> = {
  name: string,
  extraInfo: T
}


const me: Player2<{ favFood: string }> = {
  name: 'me',
  extraInfo: {
    favFood: 'kimchi'
  }
}
const you: Player2<null> = {
  name: 'you',
  extraInfo: null
}

타입사용 없이 제네릭 활용

const noType  = <K>(name: string, exreaInfo:K): void => {
  console.log(exreaInfo)
 }
 
 noType('하이',{favFood:'하이'})
 noType<string>("하이",'하이')  // 타입 직전지정

any와의 차이

인자들과 반환값에 대하여 형태(타입)에 따라 그에 상응하는 형태(타입)를 갖을 수 있다.

any와의 차이점은 해당 타입에 대한 정보를 잃지 않는다.
any는 any로서 밖에 알 수 없지만 generic은 타입 정보를 알 수 있다.

위의 예시에서

any를 사용할경우 a.toUpperCase(); 를 사용하면 에러가 뜨지않지만
Generic을 사용할경우 a.toUpperCase();를 입력하면 에러가 뜨면서 보호가됨

profile
메모장

0개의 댓글