Typescript 함수

HOONEY·2022년 6월 16일
0

Typescript

목록 보기
6/7
post-thumbnail

Call Signatures

// 기본
function add(a: number, b: number) {
	return a+b;
}

// arrow function
const add = (a: number, b: number) => a+b;

// 파라미터에 타입 넣지 않기 위한 방법(type 미리 만들어둠)
type Add = (a: number, b: number) => number;

const add: Add = (a, b) => a+b;
  • vs code에서 함수에 마우스를 호버하면 call signatures가 나타난다.

Overloading

  • Overloading은 여러 개의 call signatures가 있을 경우 발생한다.
  • 주로 직접 사용하기 보다는 외부 라이브러리에서 볼 수 있다.
// 이거와
type Add = (a: number, b: number) => number;

// 이거는 같다.
type Add = {
	(a: number, b: number): number
    (a: number, b: string): number
}
// 이게 같은 이유는 Overloading 때문
const add: Add = (a, b) => {
	if (typeof b === "string") return a	
    return a + b;
}
  • Overloading 사용 예시
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)
}
  • Overloading 사용 예시2
type Add = {
	(a: number, b: number): number
    (a: number, b: string, c: number): number
}
// 같은 이름의 call signatures 이면서 파라미터 갯수가 다를 경우
const add: Add = (a, b, c?: number) => {
    if (c) return a+b+c;
    return a+b;
}

// 호출
add(1,2,3);
add(1,2);

Polymorphism

  • call signatures를 직접 만들지 않고 generic 타입을 받도록 하여 편하게 작업 가능 -> 다형성!
// 불편함
/*type SuperPrint = {
	(arr: number[]): void
    (arr: boolean[]): void
    (arr: string[]): void
}*/
// generic 사용
type SuperPrint = {
	<T>(arr: T[]): void
}

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

// 호출
superPrint([1, 2, 3, 4]);
superPrint([true, false, true, true]);
superPrint(["1", "2", "3", "4"]);
superPrint(["1", "2", true, false);

Generics Recap

  • generic은 signature를 생성해줄 수 있는 도구!
// 선언
type SuperPrint = <T, M>(a: T[], b: M) => T

const superPrint: SuperPrint = (a) => a[0];

// 호출
const a = superPrint([1, 2, 3, 4], "X");
const b = superPrint([true, false, true, true], 1);
const c = superPrint(["1", "2", "3", "4"], false);
const d = superPrint(["1", "2", true, false], []);

결론

  • Typescript를 오랜만에 공부했다.
  • 처음 공부할 때보다 더 수월하게 공부했으며, 이해가 안되던 부분도 이해할 수 있었다.
profile
기록하는 블로그

0개의 댓글