타입스크립트- Call signature,Overloading,Generics

nevermind·2022년 11월 18일
0

typescript

목록 보기
7/12

Call signature

  • 함수의 매개변수의 타입과 반환 값의 타입을 모두 type으로 미리선언
const add = (a:number,b: number) => a+b;
//아래와 같이 바꿀 수 있다
 
type Add = (a:number, b:number) => number
//이렇게 써도 됨 type Add = {(a:number, b:number):number}

const add:Add = (a,b) => a+b
  • 여기서 헷갈렸던 부분!
    - const add:Add = (a,b) => a+b !== const add:Add = (a,b) => {a+b} 같지 않다
    • const add:Add = (a,b) => a+b는
      function add(a, b) {return (a+b)}
      
      와 같다
    • const add:Add = (a,b) => {a+b} 는
      function add(a, b) {a+b;}
      결과가 달라진다
    • 즉 화살표함수에서 { }를 사용하면 그 안의 값은 반환이 아니라 함수 내부 내용으로 처리가 되기에 반환값이 없는 void로 처리가 된다

Overloading

  • 외부 라이브러리에 자주 보이는 형태
  • 하나의 함수가 복수의 Call signature을 가질 때 발생
type Add = { 
  (a:number, b:number):number, 
  (a:number, b:string):number
}

const add:Add = (a,b) => {
  if(typeof b === 'string') return a
  //a+b가 안될 때 예외처리를 미리 해준다
  return a+b
}
  • 매개변수의 수가 다른 경우 예외처리해준다
type Add2 = {
(a: number, b: number): number,
(a: number, b: number, c: number): number
}

//옵션으로 예외처리
const add2: Add2 = (a, b, c?: number) => {
if (c) return a + b + c;
return a + b;
}
  • 외부 라이브러리에서의 예
//Next.js를 쓸 때
router.push("/home");

router.push({
path: "/home",
state: 1
});

/////타입지정
type Config = {
path: string,
state: number
}

type Push = {
(config: Config): void,//void는 아무것도 return하지 않는다
(config: string): void
}

const push: Push = (config) => {
   //예외처리를 해준다
if (typeof config === "string") console.log(config);
else console.log(config.path);
}

Polymorphism Generics

  • polymorphism : 인자들과 반환값에 대하여 형태(타입)에 따라 그에 상응하는 형태(타입)를 가짐
  • 어떤 타입이든 받을 수 있는 점이 any와 같지만 함수 반환하는 데에 있어서 any는 받았던 인수들의 타입을 활용 못함 => 즉 generics는 타입에 대한 정보를 다른 쪽으로 전달할 수 있는 점이 다름
  • ts가 우리를 위해서 일해준다!
type SuperPrint={
(arr:T[]):T;
}

const superPrint:SuperPrint=(arr)=>{
return arr[0]
}

const a=superPrint([1,2,3])
const b=superPrint([true,false,true])
const c=superPrint(["a","b"])
const d=superPrint([1,2,"a","b",true])
  • type a = <T>(a:T[]) => T <T>로 placeholder해준다
  • 여러개의 Generics 사용가능
    type SuperPrint = { (arr: T[], x: M): T }

출처: 노마드코더 타입스크립트 https://nomadcoders.co/typescript-for-beginners

profile
winwin

0개의 댓글