[TS] Call Signature

HOU·2022년 7월 21일
0

JavaScript

목록 보기
14/20
post-thumbnail

사용 환경

Ts playground


Call Signature

Call 부른다. Signature 기호
기호를 부른다. 타입을 부른다 정도로 설명할 수 있을 거 같다.

보통 함수를 사용할 때 아래와 같이 파라미터 타입을 정해주고 사용했다

const add = (a:number, b:number):number => {
  return a+b
}

이것은 아래처럼 바꿀 수 있다.

const add = (a:number, b:number) => {
  return a+b
}

똑똑한 Typescript는 abnumber 타입인걸 확인하고 그 결과 add의 타입도 number 인것을 파악했다. 하지만

const add = (a, b) => {
  return a+b
} //오류가 발생한다.

위와 같은 코드는 오류가 발생한다. Typescript가 유추할 방법이없다. 이걸 가능하는게 바로
Call Signature이다.

//call signature
type Add = {(a:number, b:number):number}

const add:Add = (a, b) => {
  return 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
}

b가 스트링이면 결과는 a만 return되고 숫자일 경우 ab가 합쳐진 결과가 나온다.

아래와 같이 Object 에도 사용될 수 있다.

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, config.state)
  }
}

push({path:"./home" ,state:{person:"hou"}})

결과값은 아래와같이 나온다!

Over Loading

오버로딩은 이름이 같은 함수에 파라미터만 변경하여 사용하는 것으로 한 함수를 여러 파라미터를 받아 사용할때 쓰는 개념이다.

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

const add1:Add = (a, b, c?:number) => {
    if (c) return a + b + c;
    return a+b
}

위와 같이 코드를 짜면 c가없는 경우엔 a+b가 return 되고 c가 있는경우 a+b+c가 return 된다.

Polymorphism(다형성)

Poly 많은 morphology 형태
많은 형태를 의미한다. Typescript에서 다형성은 무엇일까? 여러가지 타입들을 다양하게 사용할 수 있는것 아닐까? 그러면 저번 포스팅했던 any가 있자나 라고 생각했다. 하지만 any는 다형성이 아니다. 그냥 형태가 없는 놈일뿐... 내생각! any보다 좋은 generic이라는게 있다 자바 개발자들은 많이 들어봣을거 같은데 한번 알아보자!

Generic

아래 코드를 보면 좀 쉽게 이해가 가지 않을까

type SuperPrint ={
  (a : number[]) : void
  (a : boolean[]) : void
  (a: string[]) : void
  (a: (number|boolean|string)[]): void
}
const superPrint: SuperPrint = (a) => a[0]

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

OH MY GOD! 타입 지옥에 빠질거 같은 기분이다.
이것을 좀 더 수월하게 하기 위해서 generic이라는 것을 제공한다. 아래와같이 말이다.

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

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

5줄의 코드가 단 한줄로 줄어들었다 아주 보기 좋다! <> 안에 값은 아무 값이나 넣어도 된다. 보통 T를 많이 사용한다고 한다.

generic 사용법

함수!

function superPrint<T,M>(a: T[], b?:M){
    return a[0]
}

superPrint([1,2,3,4], "x"); --> 1
superPrint([true, false, true]); --> true
superPrint(["a", "b", "c"]); --> "a"
superPrint([1, 2, true, false, "a"]) --> 1

위에 함수처럼 generic을 두개 입력하여 parameter를 두개 사용할 수 있다.

Object

type Player<E> = {
    name:string
    extraInfo:E
}
type NicoExtra = {
    favFood:string
}
type NicoPlayer = Player<NicoExtra>

const nico :NicoPlayer = {
    name: "nico",
    extraInfo: {
        favFood:"kimchi"
    }
}

const lynn: Player<null> = {
    name:"lynn",
    extraInfo:null
}

type을 중첩해서 계속 지정해줫다! 이런식으로도 사용할 수 있다.

generic 사용법

type A = Array<number>
let a:A = [1, 2 ,3, 4, 5]
//generic사용법 3 arr:number[]
function printAllNumbers(arr : Array<number>){

}

정리

1.Callsignature는 타입을 정의하는 방법이다. type으로 선언한다.
2. Overloading 오버로딩은 이름은 같은 함수에 여러개의 파라미터를 받을 수 있다.
3. Polymorphism 여러가지 타입들을 확인해준다. genric이라고 부르며! <> 태그안에 원하는 아무값이나 넣을수 있다. any와는 엄연히 들다.

참조

니코샘 타입스크립트강의

profile
하루 한 걸음 성장하는 개발자

0개의 댓글