rhanziy

TS - 함수의 type alias 본문

Html_css_js

TS - 함수의 type alias

rhanziy 2023. 1. 5. 18:13

type 작명 = (파라미터 type)  => return type; 으로 함수의 alias타입을 지정해준다.

type Func3 = (a :string) => number;

let func3 :Func3 = (a) => { return 10;}

 

이해하기 쉽게 예시를 들어보면

type UserInfo = {
    name : string,
    age : number,
    plusOne : (a:number) => number,
    changeName : () => void 
}

let userInfo :UserInfo = {
    name : 'kim',
    age : 30,
    plusOne(a){
        return a + 1;
    },
    changeName : () => {
        console.log('안녕');
    }

}

 

 

조금 복잡하지만 함수의 alias type과 콜백함수를 구현한 코드

cutZero 함수는 입력된 문자의 첫번째 값이 0이면 지워주는 함수.

removeDash 함수는 입력된 문자 중 '-' 값을 지워주는 함수.

type CutZero = (a :string) => string;
type RemoveDash = (a :string) => number;

let cutZero :CutZero = function(a){
    if(a[0] == '0'){
        return a.slice(1, a.length);
    } else {
        return a;
    }
    
}

let removeDash :RemoveDash = function(a){
   let newA = a.replace(/-/g, "");
   return parseFloat(newA);
}


function phoneNum(a :string, cutZero :CutZero, removeDash :RemoveDash) {
    let result = cutZero(a);
    let result2 = removeDash(result);
    console.log(result2);
};

phoneNum('010-3333-2222', cutZero, removeDash) 를 실행하면

cutZero에 입력된 문자 값이 들어가고, 그 결과를 result에 담아 removeDash의 파라미터로 보낸다.

함수안의 함수를 실행시키는 법! removeDash는 콜백함수이다.

Comments