[Typescript] 89. Hard - Currying 1
typescript Hard 89
2023-09-14 08:59:11 时间
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>>,
]
相关文章
- [Typescript] 95. Hard - Required Keys
- [Typescript] 68. Medium - Fill
- [Typescript] TypeScript module Augmentation
- [Typescript] 64. Hard - AllCombinations
- [Typescript] Get a TypeScript package ready for release to NPM
- [Typescript] Abstract Classes
- [Typescript] Making TypeScript Stick - 5 - Extends
- [Typescript] Narrow the unknown Type with TypeScript's Assertion Functions
- [Typescript] Make your optional fields required in TypeScript
- [Typescript] Make TypeScript Class Usage Safer with Strict Property Initialization
- [TypeScript] Type check JavaScript files using JSDoc and Typescript 2.5
- [Typescript] Generics using TypeScript
- [Typescript] Sorting arrays in TypeScript
- [Typescript] Function defination
- [Typescript] 139. Extreme - Slice
- [Typescript] 113. Hard - Pinia
- [Typescript] getProp<T, P extends PathKeys<T>>(obj: T, path: P): PropType<T, P>
- [Typescript] 115. Hard - Drop String
- [Typescript] 104. Hard - Tuple to Enum Object
- [Typescript] The naked type
- [Typescript] Making TypeScript Stick - 3
- [TypeScript] Make typescript stick - 2
- [Typescript] Prevent Type Widening of Object Literals with TypeScript's const Assertions
- [TypeScript] Type Definitions and Modules
- TypeScript的非空断言操作符(感叹号)
- TypeScript值比较、泛型函数类型和签名