[Typescript] 89. Hard - Currying 1

TypeScript 4.0 is recommended in this challenge

Currying is the technique of converting a function that takes multiple arguments into a sequence of functions that each take a single argument.

For example:

const add = (a: number, b: number) => a + b
const three = add(1, 2)

const curriedAdd = Currying(add)
const five = curriedAdd(2)(3)

The function passed to Currying may have multiple arguments, you need to correctly type it.

In this challenge, the curried function only accept one argument at a time. Once all the argument is assigned, it should return its result.

 

/* _____________ Your Code Here _____________ */

type Curried<F> = F extends (...args: infer Args) => infer RT
  ? Args extends [infer First, ...infer REST]             
    ? REST['length'] extends 0
      ? (a: First) => RT                                    
      : (a: First) => Curried<(...args: REST) => RT>     
    : () => RT
  : never;
declare function Currying<Fn>(fn: Fn): Curried<Fn>


/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

const curried1 = Currying((a: string, b: number, c: boolean) => true)
const curried2 = Currying((a: string, b: number, c: boolean, d: boolean, e: boolean, f: string, g: boolean) => true)
const curried3 = Currying(() => true)

type cases = [
  Expect<Equal<
    typeof curried1, (a: string) => (b: number) => (c: boolean) => true
  >>,
  Expect<Equal<
    typeof curried2, (a: string) => (b: number) => (c: boolean) => (d: boolean) => (e: boolean) => (f: string) => (g: boolean) => true
  >>,
  Expect<Equal<typeof curried3, () => true>>,
]

 

posted @   Zhentiw  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-11-08 [Kotlin] Mapping between two entities
2018-11-08 [Node.js] Trigger a File Download in Express
2018-11-08 [WASM Rust] Create and Publish a NPM Package Containing Rust Generated WebAssembly using wasm-pack
2017-11-08 [TypeScript] Restrict null and undefined via Non-Nullable-Types in TypeScript
2017-11-08 [PWA] Deal with caches in PWA
2016-11-08 [AngularJS] Using an AngularJS directive to hide the keyboard on submit
2016-11-08 [Javascript Natural] Break up language strings into parts using Natural
点击右上角即可分享
微信分享提示