Typescript/타입스크립트 프로그래밍 연습문제

4장 연습문제

띵킹 2023. 3. 22. 20:12
//1. 함수의 반환형을 추론한다. 컨택스트로부터 매개변수 타입을 추론할 때도 있다.(ex : 콜백 함수의 경우)
//2. 제공하지 않는다. Rest 매개변수로 대체해야 한다.
//3.
type Reserve = {
    (from: Date, to:Date, destination: string): void
    (from: Date, destination : string ): void
    (destination: string ) : void
}
const reserve: Reserve = (
    fromOrDestination : Date | string,
    toOrDestination? : Date | string,
    destination? : string
) => {
    if(toOrDestination instanceof Date && fromOrDestination instanceof Date && destination !== undefined ) {
        //왕복 여행 예약
    }
    else if (typeof toOrDestination === 'string') {
        // 편도 여행 예약
    }
    else if (typeof fromOrDestination === 'string') {
        // 당일 여행 예약
    }
}
//4.
function call<T extends [unknown, string, ...unknown[]],R>(
    f: (...args: T) => R,
    ...args: T
): R {
    return f(...args)
}

function fill(length:number, value: string): string[] {
    return Array.from({length}, ()=>value)
}

function test(a: number, b: number) {
}

call(test, 1, 2) // type error
call(fill, 10, "a")

//5.
const is = <T, R extends T>(arg1:T, ...args:R[]): boolean=> {
    return args.every(_ => _ === arg1)
} 

is(10, foo) // type error
is('string', "test") //false
is('1','1','1','1') //true
is([2],[1,2,3],[1,2,3,4]) //false

4번이 너무 까다로웠다.

결국 풀이를 봤는데, 매개변수의 타입을 배열을 상속시켜 한정짓는다는 발상이 새로웠다.

 

5번의 경우 풀이랑은 다른 답이 나왔는데 각자 장단점이 있는 코드 같다.

728x90

'Typescript > 타입스크립트 프로그래밍 연습문제' 카테고리의 다른 글

7장 연습문제  (0) 2023.03.30
6장 연습문제  (1) 2023.03.29
5장 연습문제  (0) 2023.03.23
3장 연습문제  (0) 2023.03.21