TypeScript Functions

Noah·2022년 5월 12일
0

TypeScript

목록 보기
2/2
post-thumbnail

TypeScript Functions

call signatures

  • 함수 위에 마우스를 올렸을 때 보게 되는 것
  • 인자(arguments)의 타입, 함수의 반환 타입을 알려주는 것
  • 함수의 타입을 설명하고, 코드를 구현
// 적용하고 싶은 type을 먼저 선언!
type Add = (a:number, b:number) => number;
// 적용
const add:Add = (a, b) => a + b;

Overloading

  • 함수가 서로 다른 여러개의 call signatures를 가지고 있을 때 발생
  • 예시) type이 다른 경우
type Add = {
  (a:number, b:number) : number
  (a:number, b:string) : number
};
const add:Add = (a, b) => {
  if(typeof b === "string") return a
  return a + b 
}
// (parameter)b : string | number
  • 예) parameter 갯수가 다른 경우
type Add = {
  (a:number, b:number) :number
  (a:number, b:number, c:number) :number,
}
// c 는 옵션인 것을 표현 
const add:Add = (a, b, c?:number) => {
  if(c) return a + b + c
  return a + b
}

Polymorphism (다형성)

  • poly: many, several, much, multi
  • morphos, morphic: form(형태), structure(구조)

concrete type

  • number, string, boolean
  • void, unknown
type SuperPrint = {
    (arr: number[]):void
    (arr: boolean[]) :void
  	(arr: string[]) :void
}

const superPrint: SuperPrint = (arr) => {
    arr.forEach(i => console.log(i))
}

superPrint([1, 2, 3, 4])
superPrint([true, false, false])
superPrint(['1', '2', '3'])
  • 매번 알맞은 call signature 을 설정해야하기 때문에, 불편

generic type

  • Type Placeholder
  • call signature을 작성할 때, 들어올 확실한 type을 모를 때 사용
  • 사용자가 요구하는 대로 signature를 생성해줄 수 있는 도구
// Generic type
type SuperPrint = {
  	// <> 안의 이름을 자유롭게 지정이 가능
    <TypePlaceholder>(arr: TypePlaceholder[]):void
}

const superPrint: SuperPrint = (arr) => {
    arr.forEach(i => console.log(i))
}

// 기본적으로 유추한 call signature을 볼 수 있다.
// const superPrint: <number>(arr: number[])=>void
superPrint([1, 2, 3, 4])
// const superPrint: <boolean>(arr: boolean[])=>void
superPrint([true, false, false])
// generic type 2개 이상
type SuperPrint = <T,M>(a: T[], b:M) => T

const superPrint: SuperPrint = (a) = > a[0]

// const superPrint: <number, string>(a: number[], b: string) => number
superPrint([1, 2, 3], "hello")
  • 다른 예시
type Player<E> = {
  name: string
  extraInfo: E
}

type LooExtra = {
  favFood:string
}
type LooPlayer = player<LooExtra>

const loo: LooPlayer = {
  name: "loo",
  extraInfo: {
    favfood: 'kimchi'
  }
}
  • 재사용이 가능하다
profile
프론트엔드가 꿈인 코린이

0개의 댓글