AppendArgument
介绍
实现一个泛型 AppendArgument<Fn, A>
,对于给定的函数类型 Fn
,以及一个任意类型 A
,返回一个新的函数 G
。G
拥有 Fn
的所有参数并在末尾追加类型为 A
的参数。
例如
ts
type Fn = (a: number, b: string) => numbertype Result = AppendArgument<Fn, boolean>// 期望是 (a: number, b: string, x: boolean) => number
View on GitHubts
type Fn = (a: number, b: string) => numbertype Result = AppendArgument<Fn, boolean>// 期望是 (a: number, b: string, x: boolean) => number
起点
ts
/* _____________ Your Code Here _____________ */typeAppendArgument <Fn ,A > = any/* _____________ Test Cases _____________ */typeCase1 =AppendArgument <(a : number,b : string) => number, boolean>typeResult1 = (a : number,b : string,x : boolean) => numbertypeCase2 =AppendArgument <() => void, undefined>typeResult2 = (x : undefined) => voidtypecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Case1 ,Result1 >>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Case2 ,Result2 >>,Unused '@ts-expect-error' directive.2578Unused '@ts-expect-error' directive.// @ts-expect-error AppendArgument <unknown, undefined>,]
take the challengets
/* _____________ Your Code Here _____________ */typeAppendArgument <Fn ,A > = any/* _____________ Test Cases _____________ */typeCase1 =AppendArgument <(a : number,b : string) => number, boolean>typeResult1 = (a : number,b : string,x : boolean) => numbertypeCase2 =AppendArgument <() => void, undefined>typeResult2 = (x : undefined) => voidtypecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Case1 ,Result1 >>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Case2 ,Result2 >>,Unused '@ts-expect-error' directive.2578Unused '@ts-expect-error' directive.// @ts-expect-error AppendArgument <unknown, undefined>,]
解决方案
Spoiler warning // Click to reveal answer
ts
typeAppendArgument <Fn ,A > =Fn extends (...args : inferArgs ) => inferR ? (...args : [...Args ,A ]) =>R : never;
ts
typeAppendArgument <Fn ,A > =Fn extends (...args : inferArgs ) => inferR ? (...args : [...Args ,A ]) =>R : never;