[타입스크립트 기초2]

킹뎡·2022년 9월 30일

call signiture


타입 스크립트에게 이 함수가 어떻게 호출되는지 설명해준다.

type Add = (a:number, b:number) => number;

const add:Add = (a, b) => a + b

오버로딩

함수가 서로 다른 여러개의 콜 시그니쳐를 가지고 있을 때 발생된다.

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
}
type Config = {
	path:string,
	state:object
}

type Push = {
	(path:string):void
	(config:Config):void
}

const push: Push = (config) => {
  if(typeof config === "string") {console.log(config)}
  else{
    console.log(config.path/*path or state*/)
  }
}
type Add ={
  (a:number, b:number) : number
  (a:number, b:number, c:number): number,
}
const add:Add = (a, b, c?:number) => {
  return a+b
}

파라미터의 갯수가 다르다? 추가적으로 타입을 줘야하고, 선택사항이라는 것을 알려주어야 한다.

-3.2 Polymorphism-
다형성
제네릭이란? 타입의 placeholder 같은 것. concrete type을 사용하는 것 대신 쓸 수 있다. 타입스크립트로 플레이스 홀더를 작성할 수 있고, 그게 뭔지 추론해서 함수를 사용하는 것.
우리가 콜 시그니쳐를 작성할 때, 들어올 확실한 타입을 모를 때 제네릭을 사용한다.

type SuperPrint = {
	<TypePlaceholder>(arr: TypePlaceholder[]): TypePlaceholder
}
    
const superPrint: SuperPrint = (arr) =>{
  arr.forEach(i => console.log(i))
}

또는

function superPrint<T>(a: T[]){
  return a[0]
}

superPrint([1, 2, 3, 4])
superPrint([true, false, true])
superPrint(["a", "b", "c"])
superPrint([1, 2, true, false, "hello"])

의문 : 제네릭을 쓰면 타입스크립트를 쓸 이유가 없지 않나?? any도 있고,,

제네릭은 내가 요구한 대로 시그니쳐를 생성해줄 수 있는 도구.
라이브러리를 만들거나, 다른 개발자가 사용할 기능을 개발하는 경우엔 제네릭이 유용하다. 상속이나 재사용 같은 것도 가능하네,,, 아직 이해가 부족,,

profile
무럭무럭 자라기

0개의 댓글