TIL 11/6

Rami·2024년 11월 6일

TodayILearn

목록 보기
28/61

3.0 call signature

function 함수 & 화살표 함수

function add(a:number, b:number){
return a + b
}
const addd = (aa:number, bb:number) => aa + bb

call signature

type Add = (a:number, b:number) => number
const adddd: Add = (a, b) => a + b

3.1 overloading

TypeScript 함수 오버로딩: Push 타입 예시

TypeScript에서 함수 오버로딩을 통해 함수가 여러 가지 입력 형태를 받아 다양한 상황에서 사용할 수 있습니다. 예제로 Push 타입을 정의해 보겠습니다.

1. Config 타입 정의

먼저 Config 타입을 정의합니다. 이 타입은 pathstate라는 두 가지 속성을 가진 객체 형태입니다.

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

2. Push 타입 정의

Push 타입은 함수가 두 가지 형태로 호출될 수 있도록 설정합니다. 이때 호출 시그니처(call signature)를 사용하여 push 함수가 각각 문자열 또는 Config 객체를 인자로 받을 수 있게 합니다.

  • (path: string): voidstring 타입의 path만 받는 형태
  • (config: Config): voidConfig 타입의 객체를 받는 형태
type Push = {
    (path: string): void
    (config: Config): void
}

3. Push 타입 사용 예시

Push 타입을 사용하여 push 함수를 정의하고, 두 가지 형태의 인자를 처리할 수 있게 합니다.

const push: Push = (arg: string | Config): void => {
    if (typeof arg === "string") {
        console.log(`Path로 이동: ${arg}`);
    } else {
        console.log(`Path: ${arg.path}, 상태:`, arg.state);
    }
};

// 사용 예시
push("home"); // Path로 이동: home
push({ path: "home", state: { loggedIn: true } }); // Path: home, 상태: { loggedIn: true }

4. 동작 방식 정리

  • push("home"): 문자열 형태로 호출하면 path 정보만 가지고 이동합니다.
  • push({ path: "home", state: { loggedIn: true } }): Config 타입의 객체를 넣어 호출하면 path와 함께 추가적인 state 정보를 가지고 동작합니다.

이렇게 Push 타입으로 설정된 push 함수는 서로 다른 두 가지 입력 형태를 유연하게 처리할 수 있습니다.


3.4 conclusion

type으로 코드 간결하게 만들기

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

const nico : Player<{favFood:string}> = {
    name: "nico",
    extraInfo: {
        favFood: "hamburger"
    }
}

원하는대로 코드 확장 가능

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

type NicoExtra = {
    favFood: string;
}
type NicoPlayer = Player<NicoExtra>

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

4.1 Dict recap

4.0~4.1 어렵다 꼭 다시보자

type Words = {
    [key:string]:string
}


class Dict {
    private words: Words
    constructor(){
        this.words = {}
    }
    add(word:Word){
        if(this.words[word.term] === undefined){
            this.words[word.term] = word.def;
        }
    }
    def(term:string){
        return this.words[term]
    }
}

class Word {
    constructor(
        public term : string,
        public def: string
    ){}
}

const kimchi = new Word("kimchi", "한국의 음식");

const dict = new Dict();
dict.add(kimchi);
dict.def("kimchi")
profile
YOLO

0개의 댓글