call signature

  • call signature 타입을만드는 방법
type Add = (a:number, b:number) => number;

아래와 같이 사용할 수 있음.

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

Overloading

  • 함수가 여러개의 call signatures를 가지고 있을 때 발생시킴.

안좋은 예시

type Add = {
	(a:number, b:number) : number
    (a:number, b:string) : number
}

const add:Add = (a,b) => {
	if(type b === "string") retrun a
    return a + b
}

next js 에서의 오버로딩

//push의 다양한 기능
Route.push({
path: "/home",
state: 1
}) 

Router.push("/home")

제대로 된 오버로딩의 예시

type Config = {
path: string,
state: number
}

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

const push: Push = (config) => {
if (typeof config === "string") console.log(config);
else console.log(config.path);
}

//파라미터의 갯수가 달라도 된다
type Add ={
(a:number,b:number):number;
(a:number,b:number,c:number):number;
}
//a , b만 return 하고 싶을 때 c까지 확인하고 싶을 때 다양하게 사용하면 된다.
const add:Add=(a,b,c?:number)=>{
if(c) return a+b+c;
return a+b;
}

add(1,2)
add(1,2,3)

Polymorphism (다형성)

  • 인자들과 반환값에 대하여 여러 타입을 받아들임으로써 여러 형태를 가지는 것

generic type

  • 타입의 placeholder 같은 것
    call signature를 작성할 때 받아올 타입을 확실하게 모를때 generic사용함

generic type을 쓰지않은 잘못된 예시

❌ type SuperPrint = {
	(arr: number[]):void
    (arr: boolean[]):void
	(arr: string[]):void
	(arr: (number | boolean)[]):void
}
 
🆗 type SuperPrint = {
	<제네릭이름 보통 T or V>(arr: 제네릭이름[]):제네릭이름
} // 제네릭을 받는걸 알려준다.

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

superPrint([1,2,3,4])
superPrint([true, false])
superPrint(["a", "b"])
superPrint([1,2,true, false])
profile
https://lia-portfolio.vercel.app/

0개의 댓글