개발

Typescript - Functions

Hanagertudekim 2022. 8. 25. 21:41

 

Functions

  1. call signature
    1. function의 type을 미리 지정해줄수있음
    2. type 지정과 function 지정을 분리시킬수있다.
    3. 만약 react.js 로 function을 짜고 props로 보내줄때, 이 call signature 을 보내줘야한다.
const Add = (a: number, b:number) => number

const add: ADD = (a, b) => {  }



  1. Over loading
    1. 오버로딩은 함수가 여러개의 call signature 을 가질때 발생한다.



  2. polymorphism
    1. 여러가지 다른 구조들
    2. 여러 타입이 들어올 가능성을 열어둘수있음 —> Generic 을 받음
    3. Generic은 기본적으로 placeholder 을 사용해서 내가 사용한 코드를 기준으로 type을 바꿔줌.
      1. any 보다는 generic을 사용하길 권장
      2. → 만약 any 상태에서 toUpperCase() 를 하면 어떤 type이 들어와도 다 가능하지만, generic 이면 알아서 type을 유추해주기 때문에 더 안정성이 높다


    4. 타입스크립트가 타입을 유추할수있도록 해줌
    type superPrint = {
    	(arr: number[]) : void
    }
    
    const SuperPrint: superPrint = (arr) => {
    	arr.map(i => console.log(i))
    }
    
    SuperPrint([1,2,3]) // 1, 2, 3
    SuperPrint([1,2,"hello]) // error
     --> 이런 함수에서 여러 인자의 type 을 받을 가능성을 열어두려면 
    
    -----------------------------------------------
    
    type superPrint = {
    	<T>(arr: T[]) : T
    }
    
    const SuperPrint: superPrint = (arr) => {
    	arr.map(i => console.log(i))
    }
    
    SuperPrint([1,2,3]) // 1, 2, 3 (num type을 유추함) 
    SuperPrint(["first", "hene", "hello"]) // first, hene, hello (str type을 유추함) 
    

    • 실제로 사용하게 될때
    function superPrint<T> = (a: T[]) => {
    	return a[0];
    }
    

'개발' 카테고리의 다른 글

TypeScript - type  (0) 2022.08.25
< html > vs code에서 유용한 html 자동완성  (0) 2022.06.24
<html> herf, src, url 차이점  (0) 2022.06.24
< React > react 에서 Event 다루기  (0) 2022.06.24
< React > Router 정리  (1) 2022.06.24