跳到主要内容

AppendArgument

介绍

实现一个泛型 AppendArgument<Fn, A>,对于给定的函数类型 Fn,以及一个任意类型 A,返回一个新的函数 GG 拥有 Fn 的所有参数并在末尾追加类型为 A 的参数。

例如

ts
type Fn = (a: number, b: string) => number
type Result = AppendArgument<Fn, boolean>
// 期望是 (a: number, b: string, x: boolean) => number
ts
type Fn = (a: number, b: string) => number
type Result = AppendArgument<Fn, boolean>
// 期望是 (a: number, b: string, x: boolean) => number
View on GitHub

起点

ts
/* _____________ Your Code Here _____________ */
 
type AppendArgument<Fn, A> = any
 
/* _____________ Test Cases _____________ */
 
type Case1 = AppendArgument<(a: number, b: string) => number, boolean>
type Result1 = (a: number, b: string, x: boolean) => number
 
type Case2 = AppendArgument<() => void, undefined>
type Result2 = (x: undefined) => void
 
 
 
type cases = [
Expect<Equal<Case1, Result1>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Case2, Result2>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
// @ts-expect-error
Unused '@ts-expect-error' directive.2578Unused '@ts-expect-error' directive.
AppendArgument<unknown, undefined>,
]
 
ts
/* _____________ Your Code Here _____________ */
 
type AppendArgument<Fn, A> = any
 
/* _____________ Test Cases _____________ */
 
type Case1 = AppendArgument<(a: number, b: string) => number, boolean>
type Result1 = (a: number, b: string, x: boolean) => number
 
type Case2 = AppendArgument<() => void, undefined>
type Result2 = (x: undefined) => void
 
 
 
type cases = [
Expect<Equal<Case1, Result1>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Case2, Result2>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
// @ts-expect-error
Unused '@ts-expect-error' directive.2578Unused '@ts-expect-error' directive.
AppendArgument<unknown, undefined>,
]
 
take the challenge

解决方案

Spoiler warning // Click to reveal answer
ts
type AppendArgument<Fn, A> = Fn extends (...args: infer Args) => infer R ? (...args: [...Args, A]) => R : never;
 
ts
type AppendArgument<Fn, A> = Fn extends (...args: infer Args) => infer R ? (...args: [...Args, A]) => R : never;
 
view more solutions