타입챌린지 : 3312-Parameters (easy)
이 글은 제가 타입챌린지를 하면서 해석한 내용을 적는 글입니다. 틀린 내용이 있으면 댓글 달아주시면 감사하겠습니다.
GitHub - type-challenges/type-challenges: Collection of TypeScript type challenges with online judge
Collection of TypeScript type challenges with online judge - GitHub - type-challenges/type-challenges: Collection of TypeScript type challenges with online judge
github.com
type MyParameters<T extends (...args: any[]) => any> = T extends (...args: infer K) => any ?
K : never;
// test case
const foo = (arg1: string, arg2: number): void => {}
const bar = (arg1: boolean, arg2: { a: 'A' }): void => {}
const baz = (): void => {}
type cases = [
Expect<Equal<MyParameters<typeof foo>, [string, number]>>,
Expect<Equal<MyParameters<typeof bar>, [boolean, { a: 'A' }]>>,
Expect<Equal<MyParameters<typeof baz>, []>>,
]
함수의 파라미터의 타입을 배열 형태로 뽑는 타입
type MyParameters : MyParameters 라는 타입을 정의한다.
<T extends (...args: any[]) => any> : T는 any를 반환하는 함수이다(정확하게 T = 함수 는 아닙니다. 어디까지나 설명을 위해서...) 이 부분은 없어도 상관이 없다. 왜냐하면 뒤에서 어차피 T가 또다시 함수를 extends하기 때문이다. T를 받을 때 함수의 형태로 받는 것을 강제할거라면 적고, 아니면 굳이 적지 않아도 된다.
T extends (...args: infef K) => any ? K : never; : T가 함수의 파라미터 타입이 K면서 any를 반환하는 함수이면, K를 리턴하고 아니면 never를 리턴한다. 쉽게 말하면, T가 함수면 해당 인자들의 K값을 리턴한다는 뜻이다. 여기서 ...args가 배열이기 때문에 K값 들도 배열에 담겨서 리턴된다.