{"id":26221696,"url":"https://github.com/snowflyt/hkt-core","last_synced_at":"2025-04-17T08:46:58.955Z","repository":{"id":275624978,"uuid":"926709522","full_name":"Snowflyt/hkt-core","owner":"Snowflyt","description":"🍃 A micro HKT (higher-kinded type) implementation for TypeScript, with type safety elegantly guaranteed.","archived":false,"fork":false,"pushed_at":"2025-03-19T06:56:52.000Z","size":875,"stargazers_count":46,"open_issues_count":2,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-08T09:08:15.737Z","etag":null,"topics":["higher-kinded-types","hkt","type-level-programming","typescript"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/hkt-core","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Snowflyt.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-02-03T18:19:59.000Z","updated_at":"2025-04-07T14:28:45.000Z","dependencies_parsed_at":"2025-02-03T18:33:24.546Z","dependency_job_id":null,"html_url":"https://github.com/Snowflyt/hkt-core","commit_stats":null,"previous_names":["snowflyt/hkt-core"],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Snowflyt%2Fhkt-core","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Snowflyt%2Fhkt-core/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Snowflyt%2Fhkt-core/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Snowflyt%2Fhkt-core/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Snowflyt","download_url":"https://codeload.github.com/Snowflyt/hkt-core/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249326666,"owners_count":21251754,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["higher-kinded-types","hkt","type-level-programming","typescript"],"created_at":"2025-03-12T16:29:13.255Z","updated_at":"2025-04-17T08:46:58.940Z","avatar_url":"https://github.com/Snowflyt.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003ch1 align=\"center\"\u003e\u003cspan style=\"color: mediumseagreen\"\u003ehkt\u003c/span\u003e-core\u003c/h1\u003e\n\n\u003cp align=\"center\"\u003e\n🍃 A micro \u003cstrong\u003eHKT (higher-kinded type)\u003c/strong\u003e implementation for TypeScript, with \u003cstrong style=\"color: seagreen\"\u003etype safety\u003c/strong\u003e elegantly guaranteed.\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://www.npmjs.com/package/hkt-core\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/dm/hkt-core.svg?style=flat\u0026colorA=000000\u0026colorB=000000\" alt=\"downloads\" height=\"18\"\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://www.npmjs.com/package/hkt-core\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/v/hkt-core.svg?style=flat\u0026colorA=000000\u0026colorB=000000\" alt=\"npm version\" height=\"18\"\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://github.com/Snowflyt/hkt-core/actions/workflows/test.yml\"\u003e\n    \u003cimg src=\"https://img.shields.io/github/actions/workflow/status/Snowflyt/hkt-core/ci.yml?label=test\u0026style=flat\u0026colorA=000000\u0026colorB=000000\" alt=\"test status\" height=\"18\"\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://github.com/Snowflyt/hkt-core\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/l/hkt-core.svg?style=flat\u0026colorA=000000\u0026colorB=000000\" alt=\"MIT license\" height=\"18\"\u003e\n  \u003c/a\u003e\n\u003c/p\u003e\n\n```typescript\n/* Use as classical HKTs (e.g., @effect/typeclass or fp-ts style) */\ninterface MonadTypeClass\u003cF extends HKT\u003e {\n  of: \u003cT\u003e(a: T) =\u003e Kind\u003cF, T\u003e; // Lift a value into the monad\n  flatMap: \u003cT, U\u003e(fa: Kind\u003cF, T\u003e, f: (a: T) =\u003e Kind\u003cF, U\u003e) =\u003e Kind\u003cF, U\u003e;\n}\n\n// Create a `flatten` function for a monad from a monad type class\nconst createFlatten =\n  \u003cF extends HKT\u003e(monad: MonadTypeClass\u003cF\u003e) =\u003e\n  \u003cT\u003e(ffa: Kind\u003cF, Kind\u003cF, T\u003e\u003e): Kind\u003cF, T\u003e =\u003e\n    monad.flatMap(ffa, (x) =\u003e x);\n\n/* Use as type-level functions (e.g., HOTScript style) */\ntype ConcatNames\u003cNames extends string[]\u003e = Pipe\u003c\n  Names, // [1]\n  Filter\u003cFlow\u003cStringLength, NotExtend\u003c1 | 2\u003e\u003e\u003e, // Filter out short names\n  Map\u003cCapitalizeString\u003e, // Capitalize each name\n  JoinBy\u003c\", \"\u003e // Join names with a comma\n\u003e;\n\ntype _ = ConcatNames\u003c[\"alice\", \"bob\", \"i\"]\u003e; // =\u003e \"Alice, Bob\"\n```\n\n\u003csmall\u003e[1]: This is just an example to demonstrate type-level functions. Some types used here (e.g., \u003ccode\u003eFilter\u003c/code\u003e, \u003ccode\u003eMap\u003c/code\u003e) are not built into hkt-core. See the following sections for more details.\u003c/small\u003e\n\n## About\n\n**Higher-Kinded Types (HKT)** are a powerful concept used in many popular TypeScript libraries, including [Effect](https://github.com/Effect-TS/website/blob/269d5065c5b548bc7fccc40b164dffcdb61b16bb/content/limbo/hkt.mdx), [fp-ts](https://github.com/gcanti/fp-ts/blob/669cd3ed7cb5726024331a7a1cf35125669feb30/src/HKT.ts#L7-L70), [TypeBox](https://github.com/sinclairzx81/typebox/blob/870ab417fb69775e3b490d4457aa5963b6f16673/src/type/schema/schema.ts#L52-L58) and [HOTScript](https://github.com/gvergnaud/hotscript/blob/0bc205286bd5eea0b89fa903c411df9aca95923c/src/internals/core/Core.ts#L29-L37). While these libraries share the core idea of HKTs, their detailed implementations differ, making it difficult to share HKTs across libraries seamlessly.\n\nhkt-core solves this problem by providing a **standardized** and **type-safe** HKT implementation that works for **both classical HKT use cases** (like @effect/typeclass or fp-ts) and **type-level functions** (like HOTScript). Designed for easy integration with other libraries, it’s a **micro-library** that focuses solely on core HKT functionality without unnecessary extras.\n\nRegarding the type-level functions use case, hkt-core also aims for **_zero-cost_ abstractions** — the type computations are **optimized** to be as efficient as possible. By using hkt-core, you get a more concise way to write type-level code without worrying about slowing down TypeScript's compilation.\n\n## Installation\n\nTo install hkt-core via npm (or any other package manager you prefer):\n\n```shell\nnpm install hkt-core\n```\n\nAlternatively, if you prefer a zero-dependency approach, you can directly _copy-and-paste_ `src/index.ts` into your project, which contains all hkt-core’s code in a single file. We guarantee **_no_ breaking changes** in **releases** _without_ a major version bump.\n\n## Examples\n\nhkt-core introduces some concepts that might take a little time to fully grasp. To get the most out of it, we recommend following the [quickstart guide](#quickstart) from start to finish. However, if you’re eager to jump straight into examples, we’ve provided a few here as TypeScript playground links. These examples will give you a quick overview of what hkt-core can do:\n\n- [Create a monad typeclass with HKT](https://tsplay.dev/w2ypbW) (like in [@effect/typeclass](https://github.com/Effect-TS/effect/tree/596e051b0ced130899d35b32ed740e78326fd9a3/packages/typeclass) or [fp-ts](https://github.com/gcanti/fp-ts))\n- [Composable type-level function programming with HKTs](https://tsplay.dev/NB94zw) (like in [HOTScript](https://github.com/gvergnaud/HOTScript), but in a type-safe way)\n- [A type-level JSON parser with parser combinators](https://tsplay.dev/mbbKdm) (like in Haskell [Parsec](https://hackage.haskell.org/package/parsec))\n\n## Quickstart\n\nThis section demonstrates how to use hkt-core in two common scenarios: **classical HKTs** (like in @effect/typeclass or fp-ts) and **type-level functions** (like in HOTScript).\n\n### Use as classical HKTs 🐱\n\n\u003e [!TIP]\n\u003e\n\u003e This section assumes familiarity with **monads** and **type classes**. If you’re new to these concepts, we recommend checking out the [Effect documentation](https://github.com/Effect-TS/effect/blob/566236361e270e575ef1cbf308ad1967c82a362c/packages/typeclass/README.md) or the [fp-ts documentation](https://gcanti.github.io/fp-ts/) first — or feel free to skip to the next section, which is more beginner-friendly.\n\nLet’s start with a **monad** example. A monad is a container type that supports `flatMap` (also known as `chain`) and `of` (also known as `pure` or `return`). For example, both `Array` and `Option` are monads because they support these operations. Since TypeScript doesn’t have a built-in `Option` type, let’s define one first:\n\n```typescript\ntype Option\u003cT\u003e = { _tag: \"Some\"; value: T } | { _tag: \"None\" };\nconst some = \u003cT\u003e(value: T): Option\u003cT\u003e =\u003e ({ _tag: \"Some\", value });\nconst none: Option\u003cnever\u003e = { _tag: \"None\" };\n```\n\nNext, let’s define `of` and `flatMap` for both `Array` and `Option`. We’ll use an object to represent a monad (a monad type class):\n\n```typescript\nconst arrayMonad = {\n  of: \u003cT\u003e(a: T) =\u003e [a],\n  flatMap: \u003cT, U\u003e(fa: T[], f: (a: T) =\u003e U[]) =\u003e fa.flatMap(f),\n};\n\nconst optionMonad = {\n  of: some,\n  flatMap: \u003cT, U\u003e(fa: Option\u003cT\u003e, f: (a: T) =\u003e Option\u003cU\u003e) =\u003e\n    fa._tag === \"Some\" ? f(fa.value) : none,\n};\n```\n\nNow, let’s define a `flatten` function for a monad. Notice that `flatten` can be derived from `flatMap`:\n\n```typescript\nconst flattenArray = \u003cT\u003e(ffa: T[][]): T[] =\u003e arrayMonad.flatMap(ffa, (x) =\u003e x);\nconst flattenOption = \u003cT\u003e(ffa: Option\u003cOption\u003cT\u003e\u003e): Option\u003cT\u003e =\u003e optionMonad.flatMap(ffa, (x) =\u003e x);\n```\n\nTo avoid writing separate `flatten` functions for each monad, we can create a `createFlatten` function that generates a `flatten` function from a monad:\n\n```typescript\nconst createFlatten = (monad) =\u003e (ffa) =\u003e monad.flatMap(ffa, (x) =\u003e x);\n\nconst flattenArray = createFlatten(arrayMonad);\nconst flattenOption = createFlatten(optionMonad);\n```\n\nThe challenge is how to type `createFlatten` correctly. Ideally, `createFlatten` should accept a monad type class for a generic monad type `F\u003c~\u003e`, where `F` is a higher-kinded type. If TypeScript supported higher-kinded types natively, we could write something like this:\n\n```typescript\ninterface MonadTypeClass\u003cF\u003c~\u003e\u003e {\n  of: \u003cT\u003e(a: T) =\u003e F\u003cT\u003e;\n  flatMap: \u003cT, U\u003e(fa: F\u003cT\u003e, f: (a: T) =\u003e F\u003cU\u003e) =\u003e F\u003cU\u003e;\n}\n\nconst arrayMonad: MonadTypeClass\u003cArray\u003c~\u003e\u003e = /* ... */;\nconst optionMonad: MonadTypeClass\u003cOption\u003c~\u003e\u003e = /* ... */;\n\nconst createFlatten =\n  \u003cF\u003c~\u003e\u003e(monad: MonadTypeClass\u003cF\u003e) =\u003e\n  \u003cT\u003e(ffa: F\u003cF\u003cT\u003e\u003e): F\u003cT\u003e =\u003e\n    monad.flatMap(ffa, (x) =\u003e x);\n```\n\nWe can think of **HKTs** as functions that operate on types, or as type constructors in Haskell terms (represented as `* -\u003e *`). For example:\n\n- In Haskell, `Maybe` is a type constructor of kind `* -\u003e *`. It takes a type `a` (like `Int`) and returns a new type `Maybe a` (like `Maybe Int`).\n- Similarly, `List` is a type constructor of kind `* -\u003e *`. It takes a type `a` and returns a new type `[a]` (a list of `a`).\n\nIn the code above, `F\u003c~\u003e` represents such a type constructor. The `MonadTypeClass` accepts a type constructor `F` and uses `F\u003cT\u003e` to map a type `T` to a new type `F\u003cT\u003e`. For example:\n\n- If `F` is `Array`, then `F\u003cnumber\u003e` is `Array\u003cnumber\u003e`.\n- If `F` is `Option`, then `F\u003cstring\u003e` is `Option\u003cstring\u003e`.\n\nWe have seen the power of HKTs in action. Unfortunately, TypeScript doesn’t natively support this syntax. However, hkt-core provides a way to simulate it:\n\n```typescript\nimport { Apply, Arg0, TypeLambda1, Call1 } from \"hkt-core\";\n\n// We use untyped `TypeLambda`s for now,\n// see the next section for typed `TypeLambda`s\ninterface ArrayHKT extends TypeLambda1 {\n  return: Array\u003cArg0\u003cthis\u003e\u003e;\n}\ninterface OptionHKT extends TypeLambda1 {\n  return: Option\u003cArg0\u003cthis\u003e\u003e;\n}\n\ntype NumberArray = Apply\u003cArrayHKT, [number]\u003e; // =\u003e Array\u003cnumber\u003e\ntype StringOption = Call1\u003cOptionHKT, string\u003e; // =\u003e Option\u003cstring\u003e\n```\n\n`TypeLambda`s are the core building blocks of hkt-core. They represent **type-level functions** that operate on types. Here, we use `TypeLambda1` because both `Array` and `Option` are type constructors that take **one type argument**. To extract the type arguments passed to a `TypeLambda`, we use utility types like `Args`, `Arg0`, `Arg1`, etc.\n\nAs shown above, we can “invoke” a `TypeLambda` with type arguments using `Apply` or its aliases like `Call1`, `Call2`, etc, which correspond to type-level functions that take exactly one, two, or more type arguments. These work similarly to `Function.prototype.apply` and `Function.prototype.call` in JavaScript.\n\nFor classical HKT use cases, hkt-core provides concise aliases like `HKT` and `Kind`, which can be seen as aliases for `TypeLambda1` and `Call1` (`Kind` is actually an alias for `Call1W`, see the [Aliases for classical HKT use cases](#aliases-for-classical-hkt-use-cases) section for details). Using these aliases, we can define a `MonadTypeClass` and `createFlatten` function like this:\n\n```typescript\nimport { Arg0, HKT, Kind } from \"hkt-core\";\n\ninterface MonadTypeClass\u003cF extends HKT\u003e {\n  of: \u003cT\u003e(a: T) =\u003e Kind\u003cF, T\u003e;\n  flatMap: \u003cT, U\u003e(fa: Kind\u003cF, T\u003e, f: (a: T) =\u003e Kind\u003cF, U\u003e) =\u003e Kind\u003cF, U\u003e;\n}\n\nconst createFlatten =\n  \u003cF extends HKT\u003e(monad: MonadTypeClass\u003cF\u003e) =\u003e\n  \u003cT\u003e(ffa: Kind\u003cF, Kind\u003cF, T\u003e\u003e): Kind\u003cF, T\u003e =\u003e\n    monad.flatMap(ffa, (x) =\u003e x);\n\ninterface ArrayHKT extends HKT {\n  return: Array\u003cArg0\u003cthis\u003e\u003e;\n}\nconst arrayMonad: MonadTypeClass\u003cArrayHKT\u003e = {\n  of: (a) =\u003e [a],\n  flatMap: (fa, f) =\u003e fa.flatMap(f),\n};\n\ninterface OptionHKT extends HKT {\n  return: Option\u003cArg0\u003cthis\u003e\u003e;\n}\nconst optionMonad: MonadTypeClass\u003cOptionHKT\u003e = {\n  of: some,\n  flatMap: (fa, f) =\u003e (fa._tag === \"Some\" ? f(fa.value) : none),\n};\n\nconst flattenArray = createFlatten(arrayMonad);\n//    ^?: \u003cT\u003e(ffa: T[][]) =\u003e T[]\nconst flattenOption = createFlatten(optionMonad);\n//    ^?: \u003cT\u003e(ffa: Option\u003cOption\u003cT\u003e\u003e) =\u003e Option\u003cT\u003e\n```\n\nThis code achieves the same functionality as the imaginary syntax above, but it works in real TypeScript. By defining `ArrayHKT` and `OptionHKT` and using `HKT` and `Kind`, we can simulate higher-kinded types effectively.\n\n### Use as type-level functions ✨\n\nhkt-core isn’t just for type constructors — it also supports **_typed_ type-level functions**, which go beyond `* -\u003e *` to enable `TypeA -\u003e TypeB` transformations. This makes it possible to combine _type-level_ functions with **type-safety**, including **_generic_ type-level functions**!\n\n\u003e [!TIP]\n\u003e\n\u003e **_Generic_ type-level functions** are a powerful feature and make up almost half of hkt-core’s codebase. However, due to their complexity, they are not covered in this quickstart guide. If you are curious, check out the [Generic type-level functions](#generic-type-level-functions) section after finishing this guide.\n\nLet’s start with a JavaScript example: suppose we have an array of employee names, and we want to filter out names that are too short (which might be a bug in the data), capitalize the first letter of each name, and then join the names with a comma. We can write a function like this:\n\n```typescript\nconst capitalize = (s: string) =\u003e (s.length \u003e 0 ? s[0].toUpperCase() + s.slice(1) : \"\");\n\nconst concatNames = (names: string[]) =\u003e\n  names\n    .filter((name) =\u003e name.length \u003e 2)\n    .map(capitalize)\n    .join(\", \");\n```\n\nIn functional programming libraries like [Effect](https://github.com/Effect-TS/effect), this can be rewritten using **function composition**:\n\n```typescript\nimport { pipe } from \"effect\";\nimport { filter, map } from \"effect/Array\";\n\nconst joinBy = (sep: string) =\u003e (strings: string[]) =\u003e strings.join(sep);\n\nconst concatNames = (names: string[]) =\u003e\n  pipe(\n    names,\n    filter((name) =\u003e name.length \u003e 2),\n    map(capitalize),\n    joinBy(\", \"),\n  );\n```\n\nHere, `filter`, `map`, and `join` are higher-order functions that return new unary functions, and `pipe` chains them together. For example, `pipe(value, f, g, h)` is equivalent to `h(g(f(value)))`. Similarly, `flow` can be used to create a composed function in Effect, e.g., `flow(f, g, h)` is equivalent to `(value) =\u003e h(g(f(value)))`.\n\nBut how can we implement such a function at **type level**? While the employee names example might seem trivial at type level, consider a real-world use case: replacing names with route paths, the predicate with a route prefix, and the join function with a router builder. This becomes a type-safe routing system! For now, let’s focus on the employee names example.\n\nA practiced TypeScript developer might write the following type-level implementation:\n\n```typescript\ntype FilterOutShortNames\u003cNames extends string[]\u003e =\n  Names extends [infer Head extends string, ...infer Tail extends string[]] ?\n    Head extends `${infer A}${infer B}${infer C}` ?\n      \"\" extends A | B | C ?\n        FilterOutShortNames\u003cTail\u003e\n      : [Head, ...FilterOutShortNames\u003cTail\u003e]\n    : FilterOutShortNames\u003cTail\u003e\n  : [];\n\ntype CapitalizeNames\u003cNames extends string[]\u003e = {\n  [K in keyof Names]: Capitalize\u003cNames[K]\u003e;\n};\n\ntype JoinNames\u003cNames extends string[]\u003e =\n  Names extends [infer Head extends string, ...infer Tail extends string[]] ?\n    Tail extends [] ?\n      Head\n    : `${Head}, ${JoinNames\u003cTail\u003e}`\n  : \"\";\n\ntype ConcatNames\u003cNames extends string[]\u003e = JoinNames\u003cCapitalizeNames\u003cFilterOutShortNames\u003cNames\u003e\u003e\u003e;\n```\n\nWhile this works, it’s **_not_ reusable**. We can identify several common patterns here:\n\n- **Filter tuple elements:** Recursive types with predicates, like `FilterOutShortNames`.\n- **Map tuple elements:** Mapped types, like `CapitalizeNames`.\n- **Reduce tuple elements:** Recursive types to reduce a tuple to a single value, like `JoinNames`.\n\nIf we continue writing such code, we’ll end up with a lot of boilerplate. Just as higher-order functions like `filter`, `map`, and `reduce` simplify JavaScript code, hkt-core enables us to implement these patterns with **type-level functions** in TypeScript. But before diving into implementing these familiar functions, let’s first explore how type-level functions work in hkt-core.\n\n`TypeLambda`s are the core building blocks of hkt-core. They represent type-level functions that operate on types. To define a type-level function, we can create an interface extending `TypeLambda` and specify the `return` property, which describes how the input type is transformed:\n\n```typescript\nimport { Apply, Arg0, Arg1, Call2, Sig, TypeLambda } from \"hkt-core\";\n\ninterface Concat extends TypeLambda\u003c[s1: string, s2: string], string\u003e {\n  return: `${Arg0\u003cthis\u003e}${Arg1\u003cthis\u003e}`;\n}\n\n// Use the `Sig` utility to check the signature of a type-level function\ntype ConcatSig = Sig\u003cConcat\u003e; // =\u003e (s1: string, s2: string) =\u003e string\n\ntype _1 = Apply\u003cConcat, [\"Hello\", \"World\"]\u003e; // =\u003e \"HelloWorld\"\ntype _2 = Call2\u003cConcat, \"foo\", \"bar\"\u003e; // =\u003e \"foobar\"\n```\n\nInside a `TypeLambda`, we can access the input types using `Args\u003cthis\u003e` and its variants like `Arg0\u003cthis\u003e`, `Arg1\u003cthis\u003e`, etc. To “invoke” a `TypeLambda`, we use `Apply` or its aliases like `Call1`, `Call2`, etc., which correspond to type-level functions that take exactly one, two, or more type arguments. These utilities work similarly to `Function.prototype.apply` and `Function.prototype.call` in JavaScript.\n\nIt’s worth noting that the `Concat` type-level function we created above is `typed`, meaning the input types are strictly checked. We declared the parameters as `[s1: string, s2: string]` and the return type as `string`. The parameters are represented as a [labeled tuple](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html#labeled-tuple-elements) — these labels are just used by `Sig` to generate a human-readable signature and do not affect type checking or validation. You can remove them if you prefer.\n\nIf the input types don’t match the expected types, TypeScript will issue an error:\n\n```typescript\ntype ConcatWrong1 = Apply\u003cConcat, [\"foo\", 42]\u003e;\n//                                ~~~~~~~~~~~\n// Type '[\"foo\", 42]' does not satisfy the constraint '[s1: string, s2: string]'.\n//   Type at position 1 in source is not compatible with type at position 1 in target.\n//     Type 'number' is not assignable to type 'string'.\n\ntype ConcatWrong2 = Call2\u003cConcat, \"foo\", 42\u003e;\n//                                       ~~\n//             Type 'number' does not satisfy the constraint 'string'.\n```\n\nFor more details on type checking and validation (e.g., how incompatible arguments are handled and how to bypass strict type checking), check out the [Type checking and validation in Detail](#type-checking-and-validation-in-detail) section.\n\nhkt-core also provides type-level `Flow` and `Pipe` utility types to compose unary type-level functions. These types work similarly to `pipe` and `flow` in Effect or fp-ts:\n\n```typescript\ninterface ConcatFoo extends TypeLambda\u003c[s: string], string\u003e {\n  return: `${Arg0\u003cthis\u003e}foo`;\n}\ninterface ConcatBar extends TypeLambda\u003c[s: string], string\u003e {\n  return: `${Arg0\u003cthis\u003e}bar`;\n}\n\ntype Composed = Flow\u003cConcatFoo, ConcatBar\u003e;\ntype ComposedSig = Sig\u003cComposed\u003e; // =\u003e (s: string) =\u003e string\ntype _1 = Call1\u003cComposed, \"hello\"\u003e; // =\u003e \"hellofoobar\"\n\ntype ConcatFooBar\u003cS extends string\u003e = Pipe\u003cS, ConcatFoo, ConcatBar\u003e;\ntype _2 = ConcatFooBar\u003c\"hello\"\u003e; // =\u003e \"hellofoobar\"\n```\n\n`Flow` and `Pipe` supports up to 16 variadic type arguments, which should be sufficient for most use cases. Type checking is also performed on these utility types, ensuring that the input and output types match the expected types:\n\n```typescript\ninterface Add1 extends TypeLambda\u003c[n: number], number\u003e {\n  return: [..._BuildTuple\u003cArg0\u003cthis\u003e, void\u003e, void][\"length\"];\n}\ntype _BuildTuple\u003cLength extends number, Fill, Acc extends Fill[] = []\u003e =\n  [Length] extends [never] ? never\n  : Acc[\"length\"] extends Length ? Acc\n  : _BuildTuple\u003cLength, Fill, [...Acc, Fill]\u003e;\n\ntype ComposedWrong = Flow\u003cConcatFoo, Add1, ConcatBar\u003e;\n//                                   ~~~~\n// Type 'Add1' does not satisfy the constraint 'TypeLambda1\u003cstring, any\u003e'.\n//   Types of property 'signature' are incompatible.\n//     Type '(n: number) =\u003e number' is not assignable to type '(args_0: string) =\u003e any'.\n//       Types of parameters 'n' and 'args_0' are incompatible.\n//         Type 'string' is not assignable to type 'number'.\n\ntype ConcatFooBarWrong\u003cS extends string\u003e = Pipe\u003cS, ConcatFoo, ConcatBar, Add1\u003e;\n//                                                                       ~~~~\n// Type 'Add1' does not satisfy the constraint 'TypeLambda1\u003cstring, any\u003e'.\n//   Types of property 'signature' are incompatible.\n//     Type '(n: number) =\u003e number' is not assignable to type '(args_0: string) =\u003e any'.\n//       Types of parameters 'n' and 'args_0' are incompatible.\n//         Type 'string' is not assignable to type 'number'.\n```\n\nWhile strict type checking on type-level functions might seem restrictive in simple examples, it becomes a powerful tool for catching errors early when working with more complex types.\n\nNow let’s revisit the employee names example. With the knowledge we’ve gained, we can implement the type-level functions `Filter`, `Map`, and `Join`, and then compose them into a `ConcatNames` type-level function\n\n```typescript\n/* Define utility type-level functions */\ninterface NotExtend\u003cU\u003e extends TypeLambda\u003c[x: unknown], boolean\u003e {\n  return: [Arg0\u003cthis\u003e] extends [U] ? false : true;\n}\n\ninterface StringLength extends TypeLambda\u003c[s: string], number\u003e {\n  return: _StringLength\u003cArg0\u003cthis\u003e\u003e;\n}\ntype _StringLength\u003cS extends string, Acc extends void[] = []\u003e =\n  S extends `${string}${infer Tail}` ? _StringLength\u003cTail, [...Acc, void]\u003e : Acc[\"length\"];\n\ninterface CapitalizeString extends TypeLambda\u003c[s: string], string\u003e {\n  return: Capitalize\u003cArg0\u003cthis\u003e\u003e;\n}\n\n/* Define type-level functions for filtering, mapping and joining */\ninterface Filter\u003cF extends TypeLambda1\u003cnever, boolean\u003e\u003e\n  extends TypeLambda\u003c[xs: Param0\u003cF\u003e[]], Param0\u003cF\u003e[]\u003e {\n  return: _Filter\u003cF, Arg0\u003cthis\u003e\u003e;\n}\ntype _Filter\u003cF, TS, Acc extends unknown[] = []\u003e =\n  TS extends [infer Head, ...infer Tail] ?\n    Call1W\u003cF, Head\u003e extends true ?\n      _Filter\u003cF, Tail, [...Acc, Head]\u003e\n    : _Filter\u003cF, Tail, Acc\u003e\n  : Acc;\n\ninterface Map\u003cF extends TypeLambda1\u003e extends TypeLambda\u003c[xs: Param0\u003cF\u003e[]], RetType\u003cF\u003e[]\u003e {\n  return: _Map\u003cF, Arg0\u003cthis\u003e\u003e;\n}\ntype _Map\u003cF, TS\u003e = { [K in keyof TS]: Call1W\u003cF, TS[K]\u003e };\n\ninterface JoinBy\u003cSep extends string\u003e extends TypeLambda\u003c[strings: string[]], string\u003e {\n  return: Arg0\u003cthis\u003e extends [infer S extends string] ? S\n  : Arg0\u003cthis\u003e extends [infer Head extends string, ...infer Tail extends string[]] ?\n    `${Head}${Sep}${Call1\u003cJoinBy\u003cSep\u003e, Tail\u003e}`\n  : \"\";\n}\n\n/* We can use either `Flow` or `Pipe` to compose type-level functions */\ntype ConcatNamesFn = Flow\u003c\n  Filter\u003cFlow\u003cStringLength, NotExtend\u003c1 | 2\u003e\u003e\u003e,\n  Map\u003cCapitalizeString\u003e,\n  JoinBy\u003c\", \"\u003e\n\u003e;\ntype ConcatNamesSig = Sig\u003cConcatNamesFn\u003e; // =\u003e (xs: string[]) =\u003e string\n\ntype ConcatNames\u003cNames extends string[]\u003e = Pipe\u003c\n  Names,\n  Filter\u003cFlow\u003cStringLength, NotExtend\u003c1 | 2\u003e\u003e\u003e,\n  Map\u003cCapitalizeString\u003e,\n  JoinBy\u003c\", \"\u003e\n\u003e;\n\n/* Test the results! */\ntype Names = [\"alice\", \"bob\", \"i\", \"charlie\"];\n\ntype _1 = Call1\u003cConcatNamesFn, Names\u003e; // =\u003e \"Alice, \"Bob\", Charlie\"\ntype _2 = ConcatNames\u003cNames\u003e; // =\u003e \"Alice, \"Bob\", Charlie\"\n```\n\nSome unfamiliar utility types are used in the example above:\n\n- `Params` and its variants (`Param0`, `Param1`, etc.) are used to extract the **_declared_ parameters** of a `TypeLambda`.\n- `RetType` is used to extract the **_declared_ return type** of a `TypeLambda`.\n\nDon’t confuse these with the actual arguments passed to a `TypeLambda`, which are accessed using `Args` and its variants. You might notice that these type names are similar to `Parameters` and `ReturnType` in TypeScript — this is intentional to make them easier to remember.\n\nWe also use an interesting pattern to define types that “return” a type-level function. For example, `Filter` and `JoinBy` are just simple type-level functions, but by using generic type parameters, we can “invoke” them with different types to create different type-level functions.\n\nIn the following sections, we’ll refer to these simple type-level functions with generic type parameters (like `Filter`, `Map`, and `JoinBy`) as “**type-level function templates**”. We’ll represent their signatures as:\n\n- `Filter`: `\u003cT\u003e[predicate: (value: T) =\u003e boolean](values: T[]) =\u003e T[]`\n- `Map`: `\u003cT\u003e[f: (value: T) =\u003e U](values: T[]) =\u003e U[]`\n- `JoinBy`: `[sep: string](strings: string[]) =\u003e string`\n\nHere, the part wrapped with `[...]` represents the generic type parameters, and the part wrapped with `(...)` represents the actual parameters. If you’re looking for a truly **_generic_ type-level function**, check out the [Generic Type-Level Functions](#generic-type-level-functions) section\n\n## Documentation\n\n### Generic type-level functions\n\nWhile the “**type-level function templates**” technique as described at the end of the [quickstart guide](#use-as-type-level-functions-) is useful in some cases, it has limitations. There’re times when a _truly_ **_generic_ type-level functions** is still unavoidable.\n\nLet’s continue with the employee names example from the quickstart guide. Sometimes, the number of employees might be too large, and we only want to display the first 3 names. In common functional programming libraries, this can be achieved by using a function typically called `take`, which accepts a number `n` and a list of values, and returns the first `n` values of the list. We can define a type-level function `Take` as follows:\n\n```typescript\ninterface Take\u003cN extends number\u003e extends TypeLambda\u003c[values: any[]], any[]\u003e {\n  return: _Take\u003cArg0\u003cthis\u003e, N\u003e;\n}\ntype _Take\u003cTS extends unknown[], N extends number, Counter extends void[] = []\u003e =\n  TS extends [infer Head, ...infer Tail] ?\n    Counter[\"length\"] extends N ?\n      []\n    : [Head, ..._Take\u003cTail, N, [...Counter, void]\u003e]\n  : [];\n\ntype TakeSig = Sig\u003cTake\u003c3\u003e\u003e; // =\u003e (values: any[]) =\u003e any[]\n```\n\nSince we haven’t yet introduced the concept of _generic_ type-level functions, we simply declare the signature of `Take` as `[n: number](values: any[]) =\u003e any[]`. Let’s use it to enhance the `ConcatNames` example:\n\n```typescript\ninterface Append\u003cSuffix extends string\u003e extends TypeLambda\u003c[s: string], string\u003e {\n  return: `${Arg0\u003cthis\u003e}${Suffix}`;\n}\n\ntype ConcatNames = Flow\u003c\n  Filter\u003cFlow\u003cStringLength, NotExtend\u003c1 | 2\u003e\u003e\u003e,\n  Take\u003c3\u003e,\n  Map\u003cCapitalizeString\u003e,\n  JoinBy\u003c\", \"\u003e,\n  Append\u003c\", ...\"\u003e\n\u003e;\n\ntype Names = [\"alice\", \"bob\", \"i\", \"charlie\", \"david\"];\ntype _ = Call1\u003cConcatNames, Names\u003e; // =\u003e \"Alice, Bob, Charlie, ...\"\n```\n\nThis version works as expected, but we lose some type safety since the return type of `Take` is `any[]`. If we change `Map\u003cCapitalizeString\u003e` to something like `Map\u003cRepeatString\u003c\"foo\"\u003e\u003e`, TypeScript will not catch the error:\n\n```typescript\ninterface RepeatString\u003cS extends string\u003e extends TypeLambda\u003c[n: number], string\u003e {\n  return: _RepeatString\u003cS, Arg0\u003cthis\u003e\u003e;\n}\ntype _RepeatString\u003cS extends string, Times extends number, Counter extends void[] = []\u003e =\n  [Times] extends [never] ? never\n  : Counter[\"length\"] extends Times ? \"\"\n  : `${S}${_RepeatString\u003cS, Times, [...Counter, void]\u003e}`;\n\ntype ConcatNames = Flow\u003c\n  Filter\u003cFlow\u003cStringLength, NotExtend\u003c1 | 2\u003e\u003e\u003e,\n  Take\u003c3\u003e,\n  Map\u003cRepeatString\u003c\"foo\"\u003e\u003e,\n  JoinBy\u003c\", \"\u003e,\n  Append\u003c\", ...\"\u003e\n\u003e;\n\n// Unexpected result!\ntype _ = Call1\u003cConcatNames, Names\u003e; // =\u003e \"${string}, ...\"\n```\n\nWe can declare `Take` as a **_generic_ type-level function** to ensure type safety:\n\n```typescript\nimport type { Arg0, Sig, TArg, TypeLambdaG } from \"hkt-core\";\n\ninterface Take\u003cN extends number\u003e extends TypeLambdaG\u003c[\"T\"]\u003e {\n  signature: (values: TArg\u003cthis, \"T\"\u003e[]) =\u003e TArg\u003cthis, \"T\"\u003e[];\n  return: _Take\u003cArg0\u003cthis\u003e, N\u003e;\n}\n\ntype TakeSig = Sig\u003cTake\u003c3\u003e\u003e; // =\u003e \u003cT\u003e(values: T[]) =\u003e T[]\n```\n\nHere, instead of extending `TypeLambda`, we extend `TypeLambdaG`, where the `G` suffix stands for “**generic**”. Instead of directly declaring the signature in `TypeLambda`, we declare the **type parameter list** in `TypeLambdaG` and use the `signature` property inside the function body to define the signature. All declared type parameters can be accessed using the `TArg\u003cthis, \"Name\"\u003e` syntax within the `TypeLambdaG` body.\n\nBy defining `Take` as a _generic_ type-level function, TypeScript can now catch the error:\n\n```typescript\ntype ConcatNames = Flow\u003c\n  Filter\u003cFlow\u003cStringLength, NotExtend\u003c1 | 2\u003e\u003e\u003e,\n  Take\u003c3\u003e,\n  Map\u003cRepeatString\u003c\"foo\"\u003e\u003e,\n  // ~~~~~~~~~~~~~~~~~~~~~\n  // Type 'Map\u003cRepeatString\u003c\"foo\"\u003e\u003e' does not satisfy the constraint 'TypeLambda1\u003cstring[], any\u003e'.\n  //   Types of property 'signature' are incompatible.\n  //     Type '(xs: number[]) =\u003e string[]' is not assignable to type '(args_0: string[]) =\u003e any'.\n  //       Types of parameters 'xs' and 'args_0' are incompatible.\n  //         Type 'string[]' is not assignable to type 'number[]'.\n  //           Type 'string' is not assignable to type 'number'.\n  JoinBy\u003c\", \"\u003e,\n  Append\u003c\", ...\"\u003e\n\u003e;\n```\n\nHow does this work? Similar to generic functions in TypeScript, the **inference** mechanism of _generic_ type-level functions in hkt-core also relies on **type parameters**, which works as follows:\n\n1. Try to infer the type parameters from all the parameter types or return types that are already known.\n2. If a type parameter cannot be inferred, it defaults to its upper bound (`unknown` by default).\n3. Replace all occurrences of type parameters in the signature with their actual types.\n\nIn the example above, we already know the type of the first parameter of `Take\u003c3\u003e` is `string[]` (from the previous type-level function `Filter\u003cFlow\u003cStringLength, NotExtend\u003c1 | 2\u003e\u003e\u003e`), so we can infer the type parameter `T` in `Take` as `string`. Then, we replace `TArg\u003cthis, \"T\"\u003e` with `string` in the signature of `Take`, inferring the return type as `string[]`. This allows TypeScript to catch the error when the next type-level function `Map` expects `number[]` but receives `string[]`.\n\nHow can `Flow` pass the “known” types to `Take` in order to return the correct type? Internally, it involves a utility type called `TypeArgs`, which accepts the second argument, `Known`, as the known types, and then gives the inferred type parameters:\n\n```typescript\nimport type { TypeArgs } from \"hkt-core\";\n\ntype InferredTypeArgs1 = TypeArgs\u003cTake\u003c3\u003e, [string[]]\u003e; // =\u003e { readonly \"~T\": string }\ntype InferredTypeArgs2 = TypeArgs\u003cTake\u003c3\u003e, { 0: number[] }\u003e; // =\u003e { readonly \"~T\": number }\ntype InferredTypeArgs3 = TypeArgs\u003cTake\u003c3\u003e, { r: boolean[] }\u003e; // =\u003e { readonly \"~T\": boolean }\ntype InferredTypeArgs3 = TypeArgs\u003cTake\u003c3\u003e, { 0: string[]; r: number[] }\u003e; // =\u003e { readonly \"~T\": string | number }\n```\n\nHere, `Known` can be an object with integer keys and a special key `\"r\"` (tuples are also supported since they satisfy this condition), where the integer keys represent known parameter types at specific indexes, and `\"r\"` represents the known return type.\n\nUtility types like `Params`, `RetType`, and their variants also support `Known` to provide a more precise result based on the known types:\n\n```typescript\ntype InferredParams = Params\u003cTake\u003c3\u003e, { r: string[] }\u003e; // =\u003e [values: string[]]\ntype InferredRetType = RetType\u003cTake\u003c3\u003e, { 0: string[] }\u003e; // =\u003e string[]\n```\n\nThe implementation of `Flow` relies on the second argument of `RetType` to compute a more precise return type of a type-level function based on the return type of the previous one, which is how type safety is achieved.\n\nNow that we’ve explored how the **_generic_ type system** works in hkt-core, let’s look at the format of **_generic_ type parameters** in more detail:\n\n```typescript\ntype GenericTypeParams = Array\u003cSimpleTypeParam | TypeParamWithUpperBound\u003e;\n// A simple type parameter with only a name and the upper bound defaults to `unknown`\ntype SimpleTypeParam = `${Capitalize\u003cstring\u003e}`;\n// A type parameter with its name (the first element) and an upper bound (the second element)\ntype TypeParamWithUpperBound = [`${Capitalize\u003cstring\u003e}`, unknown];\n```\n\nAt the end of this section, let’s quickly skim some examples of other _generic_ type-level functions:\n\n```typescript\n// A type-level function that simply returns the input (this is already built into hkt-core)\ninterface Identity extends TypeLambdaG\u003c[\"T\"]\u003e {\n  signature: (value: TArg\u003cthis, \"T\"\u003e) =\u003e TArg\u003cthis, \"T\"\u003e;\n  return: Arg0\u003cthis\u003e;\n}\n\ntype IdentitySig = Sig\u003cIdentity\u003e; // =\u003e \u003cT\u003e(value: T) =\u003e T\n\n// A generic implementation of `Map`\ninterface Map extends TypeLambdaG\u003c[\"T\", \"U\"]\u003e {\n  signature: (\n    f: TypeLambda\u003c[x: TArg\u003cthis, \"T\"\u003e], TArg\u003cthis, \"U\"\u003e\u003e,\n    xs: TArg\u003cthis, \"T\"\u003e[],\n  ) =\u003e TArg\u003cthis, \"U\"\u003e[];\n  return: _Map\u003cArg0\u003cthis\u003e, Arg1\u003cthis\u003e\u003e;\n}\ntype _Map\u003cF, TS\u003e = { [K in keyof TS]: Call1W\u003cF, TS[K]\u003e };\n\ntype MapSig = Sig\u003cMap\u003e; // =\u003e \u003cT, U\u003e(f: (x: T) =\u003e U, xs: T[]) =\u003e U[]\n\n// A generic `Object.fromEntries` at type level\ninterface FromEntries extends TypeLambdaG\u003c[[\"K\", PropertyKey], \"V\"]\u003e {\n  signature: (\n    entries: [TArg\u003cthis, \"K\"\u003e, TArg\u003cthis, \"V\"\u003e][],\n  ) =\u003e Record\u003cTArg\u003cthis, \"K\"\u003e, TArg\u003cthis, \"V\"\u003e\u003e;\n  return: _FromEntries\u003cArg0\u003cthis\u003e\u003e;\n}\ntype _FromEntries\u003cEntries extends [PropertyKey, unknown][]\u003e = _PrettifyObject\u003c{\n  [K in Entries[number][0]]: Extract\u003cEntries[number], [K, unknown]\u003e[1];\n}\u003e;\ntype _PrettifyObject\u003cO\u003e = O extends infer U ? { [K in keyof U]: U[K] } : never;\n\ntype FromEntriesSig = Sig\u003cFromEntries\u003e; // =\u003e \u003cK extends PropertyKey, V\u003e(entries: [K, V][]) =\u003e Record\u003cK, V\u003e\ntype _ = Call1\u003cFromEntries, [[\"name\", string], [\"age\", number]]\u003e; // =\u003e { name: string, age: number }\n```\n\n### Aliases for classical HKT use cases\n\nhkt-core provide the following aliases for **type constructors**:\n\n- `HKT`, `HKT2`, `HKT3` and `HKT4` are aliases for `TypeLambda1`, `TypeLambda2`, `TypeLambda3` and `TypeLambda4`, respectively.\n- `Kind`, `Kind2`, `Kind3` and `Kind4` are aliases for `Call1W`, `Call2W`, `Call3W` and `Call4W`, respectively.\n\nThe aliases for higher-arity type constructors allow you to work with type constructors that take multiple type arguments, such as `Either\u003cL, R\u003e` or `State\u003cS, A\u003e`.\n\nThe `W` suffix in `Call*W` stands for “**widening**”, meaning type checking and validation are relaxed for arguments passed to the type-level function. For more details, see the [Bypass strict type checking and validation](#bypass-strict-type-checking-and-validation) sections.\n\n### Type checking and validation in detail\n\n#### Type checking V.S. Type validation\n\nJust like in plain TypeScript, **type checking** and **type validation** are two different concepts that are often confused.\n\nIn plain TypeScript, **type checking** refers to the _compile-time_ verification that ensures variables, function parameters, and return values match their _declared_ types. Meanwhile, **(runtime) type validation** is the _run-time_ process that confirms actual values conform to the declared types. **Type checking** is handled by the TypeScript compiler, whereas **type validation** is usually performed by custom code or 3rd-party libraries such as [Zod](https://github.com/colinhacks/zod), [TypeBox](https://github.com/sinclairzx81/typebox) and [Arktype](https://github.com/arktypeio/arktype).\n\nAlthough hkt-core is a _type-only_ library operating solely at _compile-time_, the distinction still applies. In hkt-core, **type checking** verifies that the input types provided to a type-level function are compatible with the _declared_ types, e.g., the TypeScript compiler will emit errors for signature mismatches in utilities like `Flow` or `Pipe`.\n\nOn the other hand, **type validation** in hkt-core ensures that the actual arguments passed or the computed return result match the _declared_ types, typically using utilities like `Args`, `Apply` and `Call*`. For example, if a `Concat` type-level function declared to return a `string` accidentally returns a `number`, the utility will yield `never` as the result without triggering a TypeScript error.\n\n#### Bypass strict type checking and validation\n\nThere are cases where you might want to bypass strict type checking or validation, such as when working with complex generic types or when you need to handle incompatible types. hkt-core provides a set of utilities to help you handle these cases:\n\n- `ApplyW`, `Call1W`, `Call2W`, etc. are the “**widening**” versions of `Apply`, `Call1`, `Call2`, etc. They relax both type _checking_ for arguments passed to the type-level function **and type _validation_ for the return type**.\n- `RawArgs` and its variants (`RawArg0`, `RawArg1`, etc.) are used to access the original arguments passed to a `TypeLambda`, regardless of whether they are compatible with the parameters.\n- `Params`, `RetType`, `Args` and `RawArgs` all provide their **widening** versions (e.g., `RetTypeW`, `Args0W`, `RawArgs1W`, etc.) to bypass strict type checking. Unlike `ApplyW` and its variants, which relax both type _checking_ for arguments and type _validation_ for return types, these widening utilities are simple aliases for their strict counterparts that relaxes type checking. They return `never` when the input type is not a `TypeLambda`, and do not perform additional checks or relaxations.\n\nNote that using `ApplyW` and its variants alone does not fully bypass strict type checking and validation if the body of a type-level function is still defined using `Args` and its variants. `ApplyW` and its variants only relax type _checking_ for arguments _passed_ to the type-level function and the return type, but they do not suppress type _validation_ performed by `Args` in the type-level function’s body. For example:\n\n```typescript\ninterface Concat extends TypeLambda\u003c[s1: string, s2: string], string\u003e {\n  return: `${Arg0\u003cthis\u003e}${Arg1\u003cthis\u003e}`;\n}\n\ntype ConcatWrong = ApplyW\u003cConcat, [\"foo\", 42]\u003e; // =\u003e never\n```\n\nHere, `ApplyW\u003cConcat, [\"foo\", 42]\u003e` still returns `never` because `42` is not compatible with `string`. To handle incompatible types, you can use `RawArgs` and its variants to access the original arguments:\n\n```typescript\ntype Stringifiable = string | number | bigint | boolean | null | undefined;\n\ninterface Concat extends TypeLambda\u003c[s1: string, s2: string], string\u003e {\n  return: RawArg0\u003cthis\u003e extends infer S1 extends Stringifiable ?\n    RawArg1\u003cthis\u003e extends infer S2 extends Stringifiable ?\n      `${RawArg0\u003cthis\u003e}${RawArg1\u003cthis\u003e}`\n    : never\n  : never;\n}\n\ntype ConcatWrong = ApplyW\u003cConcat, [\"foo\", 42]\u003e; // =\u003e \"foo42\"\n```\n\nHowever, you still need to manually check the types of `RawArg0\u003cthis\u003e` and `RawArg1\u003cthis\u003e` to ensure they are compatible with stringifiable types. Otherwise, TypeScript will issue an error:\n\n```typescript\ninterface Concat extends TypeLambda\u003c[s1: string, s2: string], string\u003e {\n  return: `${RawArg0\u003cthis\u003e}${RawArg1\u003cthis\u003e}`;\n  //         ~~~~~~~~~~~~~   ~~~~~~~~~~~~~\n  // Type 'RawArg0\u003cthis\u003e' is not assignable to type 'string | number | bigint | boolean | null | undefined'.\n  // Type 'RawArg1\u003cthis\u003e' is not assignable to type 'string | number | bigint | boolean | null | undefined'.\n}\n```\n\nWhile `ApplyW` might seem less useful in this example, it can be helpful in specific scenarios, such as when relaxing the return type of a type-level function:\n\n```typescript\ninterface Concat extends TypeLambda\u003c[s1: string, s2: string], number\u003e {\n  // \u003c- Return type is `number`\n  return: `${Arg0\u003cthis\u003e}${Arg1\u003cthis\u003e}`;\n}\n\ntype _1 = Apply\u003cConcat, [\"foo\", \"bar\"]\u003e; // =\u003e never, since the declared return type is `number`\ntype _2 = ApplyW\u003cConcat, [\"foo\", \"bar\"]\u003e; // =\u003e \"foobar\", since the return type is relaxed\n```\n\nAs we can see, bypassing strict type checking doesn’t always simplify things and can introduce additional complexity. These widening utilities are primarily intended for handling complex scenarios, such as when dealing with intricate variance or type constraints, and are not meant for common use cases. For example, they are useful when defining a `Flip` type-level function (already built into hkt-core) that swaps the order of two types.\n\nIn most cases, you don’t need these widening utilities if you skip declaring your type-level function’s signatures (i.e., use _untyped_ type-level functions). The parameters and return type of `TypeLambda` already default to `any`, so these widening utilities and their strict counterparts behave the same in such cases, as shown in the [Use as classical HKTs](#use-as-classical-hkts-) section.\n\n#### Type validation in `Args`\n\n`Args` and its variants (`Arg0`, `Arg1`, etc.) enforce strict type validation inside the `TypeLambda` definition. By using them, TypeScript can infer the types of the arguments against the **_declared_ parameters** correctly — meaning you don’t need to manually check the types of the arguments inside the `TypeLambda`, they just work!\n\n```typescript\ntype JoinString\u003cS1 extends string, S2 extends string\u003e = `${S1}${S2}`;\ntype JoinStringAndNumber\u003cS extends string, N extends number\u003e = `${S}${N}`;\n\n// This is not necessary\ninterface ConcatRedundant extends TypeLambda\u003c[s1: string, s2: string], string\u003e {\n  return: Arg0\u003cthis\u003e extends infer S1 extends string ?\n    Arg1\u003cthis\u003e extends infer S2 extends string ?\n      JoinString\u003cS1, S2\u003e\n    : never\n  : never;\n}\n\n// This is enough\ninterface Concat extends TypeLambda\u003c[s1: string, s2: string], string\u003e {\n  return: JoinString\u003cArg0\u003cthis\u003e, Arg1\u003cthis\u003e\u003e; // OK\n}\n\n// Incompatible type errors are caught by TypeScript\ninterface ConcatMismatch extends TypeLambda\u003c[s1: string, s2: string], string\u003e {\n  // The intermediate error messages might be confusing, just focus on the last one for the actual issue\n  return: JoinStringAndNumber\u003cArg0\u003cthis\u003e, Arg1\u003cthis\u003e\u003e;\n  //                                      ~~~~~~~~~~\n  // Type 'Arg1\u003cthis\u003e' does not satisfy the constraint 'number'.\n  //   Type 'CastArgs\u003cunknown, TolerantParams\u003cthis\u003e\u003e[1]' is not assignable to type 'number'.\n  //     Type 'TolerantParams\u003cthis\u003e[1] | (AlignArgs\u003c{}, TolerantParams\u003cthis\u003e, []\u003e extends infer CastedArgs extends ExpectedParams ? CastedArgs : never)[1]' is not assignable to type 'number'.\n  //       Type 'TolerantParams\u003cthis\u003e[1]' is not assignable to type 'number'.\n  //         Type 'string' is not assignable to type 'number'.\n}\n```\n\nWhat happens if you force-call a _typed_ type-level function with incompatible types? In such cases, incompatible arguments are replaced with `never`:\n\n```typescript\ninterface Concat extends TypeLambda\u003c[s1: string, s2: string], string\u003e {\n  return: [Arg0\u003cthis\u003e, Arg1\u003cthis\u003e]; // We just print the arguments here for demonstration\n}\n\ntype ConcatWrong = Call2W\u003cConcat, \"foo\", 42\u003e; // =\u003e [\"foo\", never]\n```\n\nThe rules for handling incompatible arguments are as follows:\n\n- If an argument is not compatible with the corresponding parameter, it is cast to `never`.\n- Redundant arguments are truncated.\n- Missing arguments are filled with `never`.\n\nHere’s an example to demonstrate these rules:\n\n```typescript\ninterface PrintArgs extends TypeLambda\u003c[a: string, b: string], string\u003e {\n  return: Args\u003cthis\u003e;\n}\n\n// Incompatible arguments are cast to `never`\ntype _1 = ApplyW\u003cPrintArgs, [\"foo\", 42]\u003e; // =\u003e [\"foo\", never]\n// Redundant arguments are truncated\ntype _2 = ApplyW\u003cPrintArgs, [\"foo\", \"bar\", \"baz\"]\u003e; // =\u003e [\"foo\", \"bar\"]\n// Missing arguments are filled with `never`\ntype _3 = ApplyW\u003cPrintArgs, [\"foo\"]\u003e; // =\u003e [\"foo\", never]\n```\n\nIf you want to access the original arguments passed to a `TypeLambda`, regardless of whether they are compatible with the parameters, use `RawArgs` or its variants instead (see the [Bypass strict type checking and validation](#bypass-strict-type-checking-and-validation) section for more details).\n\n#### Type checking and validation in `Apply` and `Call*`\n\nJust like `Args` and its variants, which coerce the arguments to match the declared parameters, `Apply` and its variants (`Call1`, `Call2`, etc.) coerce the returned value of a type-level function to match the declared return type. If the returned value is not compatible with the declared return type, it is cast to `never`:\n\n```typescript\ninterface Concat extends TypeLambda\u003c[s1: string, s2: string], string\u003e {\n  return: `${Arg0\u003cthis\u003e}${Arg1\u003cthis\u003e}`;\n}\n\n// Here we return a number, which is incompatible with the declared return type `string`\ninterface ConcatWrong extends TypeLambda\u003c[s1: string, s2: string], string\u003e {\n  return: 42;\n}\n\ntype _1 = Apply\u003cConcat, [\"foo\", \"bar\"]\u003e; // =\u003e \"foobar\"\ntype _2 = Apply\u003cConcatWrong, [\"foo\", \"bar\"]\u003e; // =\u003e never\ntype _3 = Call2\u003cConcatWrong, \"foo\", \"bar\"\u003e; // =\u003e never\n```\n\nIn the example above, `ConcatWrong` returns a number, which is incompatible with the declared return type `string`. Even though `ConcatWrong` returns a value that is not `never` (i.e., `42`), `Apply` still coerces the returned value to `never` because it is not compatible with the declared return type. The same applies to the variants of `Apply`, such as `Call2` in this case.\n\nAs is already mentioned in the [Bypass strict type checking and validation](#bypass-strict-type-checking-and-validation) section, you can use `ApplyW` and its variants if you don’t want the return value to be coerced to `never` when it’s incompatible with the declared return type.\n\nWhile the return type coercion behavior of `Apply` and its variants might cause confusion in some cases, it is useful for making TypeScript aware of type incompatibilities early on. For example, let’s revisit the `JoinBy` function from the `JoinBy` function from the [Generic type-level functions](#generic-type-level-functions) section. However, instead of using `Arg0\u003cthis\u003e extends [infer S extends string]` in the body, let’s remove the `extends string` constraint and use `Arg0\u003cthis\u003e extends [infer S]`:\n\n```typescript\ninterface JoinBy\u003cSep extends string\u003e extends TypeLambda\u003c[strings: string[]], string\u003e {\n  return: Arg0\u003cthis\u003e extends [infer S] ? S\n  : Arg0\u003cthis\u003e extends [infer Head extends string, ...infer Tail extends string[]] ?\n    `${Head}${Sep}${Call1\u003cJoinBy\u003cSep\u003e, Tail\u003e}`\n  : \"\";\n}\n```\n\nIn this case, TypeScript cannot ensure that the return type of `JoinBy` is always `string`, because it cannot infer the type of `S` in the first condition, even though we know `S` can only be `string`. If we replace `Call1` with `Call1W`, we’ll actually get an error:\n\n```typescript\ninterface JoinBy\u003cSep extends string\u003e extends TypeLambda\u003c[strings: string[]], string\u003e {\n  return: Arg0\u003cthis\u003e extends [infer S] ? S\n  : Arg0\u003cthis\u003e extends [infer Head extends string, ...infer Tail extends string[]] ?\n    `${Head}${Sep}${Call1W\u003cJoinBy\u003cSep\u003e, Tail\u003e}`\n  : //              ~~~~~~~~~~~~~~~~~~~~~~~~~\n    // Type '...' is not assignable to type 'string | number | bigint | boolean | null | undefined'.\n    //   Type 'unknown' is not assignable to type 'string | number | bigint | boolean | null | undefined'.\n    \"\";\n}\n```\n\nHowever, because we use `Call1` in the original implementation, TypeScript doesn’t report such an issue in the function. This is because `Call1` always coerces the return value to match the declared return type `string`, allowing TypeScript to ensure that the type of `Call1\u003cJoinBy\u003cSep\u003e, Tail\u003e` must be `string`, and thus no issue arises.\n\n#### Type checking and validation in _generic_ type-level functions\n\n\u003e [!TIP]\n\u003e\n\u003e This section assumes you’ve already read the [Generic type-level functions](#generic-type-level-functions) section.\n\nWhen it comes to **_generic_ type-level functions**, the type checking/validation behavior is slightly different. The general rule is _still the same_ as in previous sections, but here we have to address an issue that can often break type checking in many libraries: **variance**.\n\nConsider the generic `Map` example we skimmed at the end of the [Generic type-level functions](#generic-type-level-functions) section:\n\n```typescript\ninterface Map extends TypeLambdaG\u003c[\"T\", \"U\"]\u003e {\n  signature: (\n    f: TypeLambda\u003c[x: TArg\u003cthis, \"T\"\u003e], TArg\u003cthis, \"U\"\u003e\u003e,\n    xs: TArg\u003cthis, \"T\"\u003e[],\n  ) =\u003e TArg\u003cthis, \"U\"\u003e[];\n  return: _Map\u003cArg0\u003cthis\u003e, Arg1\u003cthis\u003e\u003e;\n}\ntype _Map\u003cF, TS\u003e = { [K in keyof TS]: Call1W\u003cF, TS[K]\u003e };\n```\n\nLet’s try to implement a “type-safe” `MyApply` based on `ApplyW`, which you might initially write like this:\n\n```typescript\ntype MyApply\u003cF extends TypeLambda, Args extends Params\u003cF\u003e\u003e = ApplyW\u003cF, Args\u003e;\n```\n\nThis works well for simple non-generic type-level functions, such as `Concat`, `Add`, or even type-level function templates like `JoinBy`. But when we apply it to `Map`, an issue arises:\n\n```typescript\ntype _ = MyApply\u003cMap, [Append\u003c\"baz\"\u003e, [\"foo\", \"bar\"]]\u003e;\n//                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n// Type '[Append\u003c\"baz\"\u003e, [\"foo\", \"bar\"]]' does not satisfy the constraint '[f: TypeLambda\u003c[x: unknown], unknown\u003e, xs: unknown[]]'.\n//   Type at position 0 in source is not compatible with type at position 0 in target.\n//     The types of 'signature' are incompatible between these types.\n//       Type '(s: string) =\u003e string' is not assignable to type '(x: unknown) =\u003e unknown'.\n//         Types of parameters 's' and 'x' are incompatible.\n//           Type 'unknown' is not assignable to type 'string'.\n```\n\nThis issue arises due to TypeScript's generic instantiation mechanism: when TypeScript cannot infer the type of a type parameter, it defaults to its upper bound (`unknown` by default). For those familiar with variance handling in TypeScript, this behavior may seem unintuitive: for covariant type parameters, this is expected, but for contravariant type parameters (like those in function parameters), they should default to `never`. This mismatch is why the issue occurs.\n\nLet’s take a look at the result of `Params\u003cMap\u003e` to better understand the root cause:\n\n```typescript\ntype ParamsOfMap = Params\u003cMap\u003e; // =\u003e [f: TypeLambda\u003c[x: unknown], unknown\u003e, xs: unknown[]]\n```\n\nThe signature of `Append\u003c\"baz\"\u003e` is `(s: string) =\u003e string`, whereas the expected signature is `(x: unknown) =\u003e unknown`. Because of the covariant nature of function parameters in TypeScript, `(s: string) =\u003e string` is not considered a subtype of `(x: unknown) =\u003e unknown`. This is because `unknown` is not assignable to `string`, which causes the type checking error.\n\nSimilar issues also occur in non-type-level functions in TypeScript. For example:\n\n```typescript\nconst apply = \u003cF extends (...args: any) =\u003e unknown\u003e(f: F, args: Parameters\u003cF\u003e): ReturnType\u003cF\u003e =\u003e\n  Function.prototype.apply(f, args);\n\nconst map = \u003cT, U\u003e(f: (x: T) =\u003e U, xs: T[]): U[] =\u003e xs.map(f);\n\napply(map, [(s: string) =\u003e s + \"baz\", [\"foo\", \"bar\"]]);\n//          ~~~~~~~~~~~~~~~~~~~~~~~~\n//          Type '(s: string) =\u003e string' is not assignable to type '(x: unknown) =\u003e unknown'.\n//            Types of parameters 's' and 'x' are incompatible.\n//              Type 'unknown' is not assignable to type 'string'.\n```\n\nThis explains why the signature of `Function.prototype.apply` in TypeScript is `(thisArg: any, argArray?: any) =\u003e any`: TypeScript cannot correctly handle the variance of function parameters, so it uses `any` to bypass strict type checking.\n\nHowever, in hkt-core, we need a solution for this problem because the only way to invoke a type-level function is through utilities like `Apply` and `Call*`. That’s where `TolerantParams` and `TolerantRetType` come in. They work as follows:\n\n1. Test the variance of each type parameter (using dummy types):\n   - If a type parameter is **covariant**, it is replaced with its **upper bound**.\n   - If a type parameter is **contravariant**, it is replaced with `never`.\n   - If a type parameter is **invariant**, it is replaced with `any`.\n2. Replace the type parameters in the signature with the corresponding types.\n3. Extract the parameters or return type from the signature.\n\nBy applying these rules, `TolerantParams` and `TolerantRetType` yield more precise results than `Params` and `RetType` when used with generic type-level functions:\n\n```typescript\nimport type { TolerantParams, TolerantRetType } from \"hkt-core\";\n\ntype TolerantParamsOfMap = TolerantParams\u003cMap\u003e; // =\u003e [f: TypeLambda\u003c[x: never], unknown\u003e, xs: unknown[]]\ntype TolerantRetTypeOfMap = TolerantRetType\u003cMap\u003e; // =\u003e unknown[]\n```\n\nWith `TolerantParams` replacing `Params`, TypeScript no longer throws errors about incompatible types — and that’s how type checking for parameters is handled in `Apply` and its variants.\n\nThe same principles apply to `Args` and its variants. `TolerantParams` is used instead of `Params` to ensure correct type validation, and we’ll skip the details here since they work in much the same way.\n\n### Common Utilities\n\nThere are many utilities commonly used in functional programming libraries. Some are very simple but are used frequently, while others may be used less often but can be quite complex to implement at the type level, especially to work well with _generic_ type-level functions. Some of these utilities are already built into hkt-core and can be seamlessly composed with your own type-level functions.\n\n#### `Always`, `Identity` and `Ask`\n\nThese utilities are simple but frequently used in functional programming libraries. Let's start with `Always`, which creates a type-level function that accepts zero arguments and always returns a constant value (this function is often called `constant` in some libraries):\n\n```typescript\ninterface Always\u003cT\u003e extends TypeLambda\u003c[], T\u003e {\n  return: T;\n}\n```\n\nThis utility is useful when a type-level function accepts a transformer function, like `TypeLambda1`, to transform the input type, but you don’t actually need to transform the input type and just want to return a constant value:\n\n```typescript\n// Suppose we have a Rust-like `Result` type\ntype Result\u003cT, E\u003e = Ok\u003cT\u003e | Err\u003cE\u003e;\n// ... and a utility type-level function `Result.Match` to match the result\nnamespace Result {\n  export interface Match\u003cOnOk extends TypeLambda1, OnErr extends TypeLambda1\u003e\n    extends TypeLambda\u003c/* ... */\u003e {\n    return: /* ... */\n  }\n}\n\ntype _ = Pipe\u003cOk\u003c\"Bob\"\u003e, Result.Match\u003cPrepend\u003c\"Mr. \"\u003e, Always\u003c\"Oops!\"\u003e\u003e\u003e; // =\u003e \"Mr. Bob\"\n```\n\nNext is `Identity`, a **_generic_ type-level function** that accepts a single argument and returns the same value:\n\n```typescript\ninterface Identity extends TypeLambdaG\u003c[\"T\"]\u003e {\n  signature: (value: TArg\u003cthis, \"T\"\u003e) =\u003e TArg\u003cthis, \"T\"\u003e;\n  return: Arg0\u003cthis\u003e;\n}\n```\n\n`Identity` serves a similar role to `Always`, useful when you need to pass a transformer function but don’t want to transform the input type:\n\n```typescript\ntype MatchResult = Pipe\u003cErr\u003c\"Oops!\"\u003e\u003e, Result.Match\u003cPrepend\u003c\"Mr. \"\u003e, Identity\u003e\u003e;\n```\n\nAnother interesting use case of `Identity` is converting a `FlatMap` operation to `Flatten` by passing `Identity` as the transformer, and you can find even more use cases in practice\n\nLastly, we have `Ask`, which behaves similarly to `Identity`, but instead of being a _generic_ type-level function, it is defined as a **type-level function template**:\n\n```typescript\ninterface Ask\u003cT\u003e extends TypeLambda\u003c[value: T], T\u003e {\n  return: Arg0\u003cthis\u003e;\n}\n```\n\n`Ask` might be the most useful utility among these three. It is commonly used with `Flow` or `Compose` to “pin” the signature of a type-level function to a specific type. For example:\n\n```typescript\nimport type { Ask, Compose, Flow, Identity } from \"hkt-core\";\n\ntype IdentityStringSig = Sig\u003cFlow\u003cAsk\u003cstring\u003e, Identity\u003e\u003e; // =\u003e (value: string) =\u003e string\n\n// You can also use `Compose`, which is used internally by `Flow`,\n// to compose exactly 2 type-level functions from **right to left**\ntype IdentityNumberSig = Sig\u003cCompose\u003cIdentity, Ask\u003cnumber\u003e\u003e\u003e; // =\u003e (value: number) =\u003e number\n```\n\nWhen composing multiple type-level functions via `Flow`, if the first function is a _generic_ type-level function, you can use `Ask` to “pin” the first type-level function to avoid type errors about incompatible types.\n\n#### `Tupled` and `Untupled`\n\n`Flow` and `Pipe` are incredibly useful for composing multiple type-level functions together, but they only work with functions that accept a single argument. If you have a type-level function that accepts multiple arguments, you can use `Tupled` to convert it into a function that accepts a single tuple argument:\n\n```typescript\ninterface Concat extends TypeLambda\u003c[s1: string, s2: string], string\u003e {\n  return: `${Arg0\u003cthis\u003e}${Arg1\u003cthis\u003e}`;\n}\ntype ConcatSig = Sig\u003cConcat\u003e; // =\u003e (s1: string, s2: string) =\u003e string\ntype _1 = Call2\u003cConcat, \"foo\", \"bar\"\u003e; // =\u003e \"foobar\"\n\ntype TupledConcat = Tupled\u003cConcat\u003e;\ntype TupledConcatSig = Sig\u003cTupledConcat\u003e; // =\u003e (args: [s1: string, s2: string]) =\u003e string\ntype _2 = Call1\u003cTupledConcat, [\"foo\", \"bar\"]\u003e; // =\u003e \"foobar\"\n```\n\nThe inverse of `Tupled` is `Untupled`, which converts a function that accepts a single tuple argument back into a function that accepts multiple arguments:\n\n```typescript\ninterface First extends TypeLambdaG\u003c[\"T\"]\u003e {\n  signature: (pair: [TArg\u003cthis, \"T\"\u003e, unknown]) =\u003e TArg\u003cthis, \"T\"\u003e;\n  return: Arg0\u003cthis\u003e[0];\n}\ntype FirstSig = Sig\u003cFirst\u003e; // =\u003e \u003cT\u003e(pair: [T, unknown]) =\u003e T\ntype _1 = Call1\u003cFirst, [42, \"foo\"]\u003e; // =\u003e 42\n\ntype UntupledFirst = Untupled\u003cFirst\u003e;\ntype UntupledFirstSig = Sig\u003cUntupledFirst\u003e; // =\u003e \u003cT\u003e(args_0: T, args_1: unknown) =\u003e T\ntype _2 = Call2\u003cUntupledFirst, 42, \"foo\"\u003e; // =\u003e 42\n```\n\n#### `Flip`\n\n`Flip` is useful when you need to swap the order of the arguments in a `TypeLambda2`. It is already built into hkt-core and can be used as follows:\n\n```typescript\ninterface Map extends TypeLambdaG\u003c[\"T\", \"U\"]\u003e {\n  signature: (\n    f: TypeLambda\u003c[x: TArg\u003cthis, \"T\"\u003e], TArg\u003cthis, \"U\"\u003e,\n    xs: TArg\u003cthis, \"T\"\u003e[],\n  ) =\u003e TArg\u003cthis, \"U\"\u003e[];\n  return: _Map\u003cArg0\u003cthis\u003e, Arg1\u003cthis\u003e\u003e;\n}\ntype _Map\u003cF, TS\u003e = { [K in keyof TS]: Call1W\u003cF, TS[K]\u003e };\n\ntype MapSig = Sig\u003cMap\u003e; // =\u003e \u003cT, U\u003e(f: (x: T) =\u003e U, xs: T[]) =\u003e U[]\ntype _1 = Call2\u003cMap, Append\u003c\"baz\"\u003e, [\"foo\", \"bar\"]\u003e; // =\u003e [\"foobaz\", \"barbaz\"]\n\ntype FlippedMap = Flip\u003cMap\u003e;\ntype FlippedMapSig = Sig\u003cFlippedMap\u003e; // =\u003e \u003cU, T\u003e(xs: U[], f: (x: U) =\u003e T) =\u003e T[]\ntype _2 = Call2\u003cFlippedMap, [\"foo\", \"bar\"], Append\u003c\"baz\"\u003e\u003e; // =\u003e [\"foobaz\", \"barbaz\"]\n```\n\nAs you can see, `Flip` swaps the order of the arguments in the function. In this example, the `Map` function originally expects the function (`f`) to be the first argument, and the array (`xs`) to be the second. After using `Flip`, the arguments are reversed so that the array comes first, followed by the function.\n\n`Flip` also works with **curried** binary type-level functions (i.e., `TypeLambda1\u003cTypeLambda1\u003e`):\n\n```typescript\n// See the next section for `Curry`\ntype CurriedMap = Curry\u003cMap\u003e;\ntype CurriedMapSig = Sig\u003cCurriedMap\u003e; // =\u003e \u003cT, U\u003e(f: (x: T) =\u003e U) =\u003e (xs: T[]) =\u003e U[]\ntype _1 = Call1\u003cCall1\u003cCurriedMap, Append\u003c\"baz\"\u003e\u003e, [\"foo\", \"bar\"]\u003e; // =\u003e [\"foobaz\", \"barbaz\"]\n\ntype FlippedCurriedMap = Flip\u003cCurriedMap\u003e;\ntype FlippedCurriedMapSig = Sig\u003cFlippedCurriedMap\u003e; // =\u003e \u003cT, U\u003e(xs: T[]) =\u003e (f: (x: T) =\u003e U) =\u003e U[]\ntype _2 = Call1\u003cCall1\u003cFlippedCurriedMap, [\"foo\", \"bar\"]\u003e, Append\u003c\"baz\"\u003e\u003e; // =\u003e [\"foobaz\", \"barbaz\"]\n```\n\n#### `Curry`\n\nCurrying is a common technique in functional programming that transforms a function accepting multiple arguments into a series of functions that each accept a single argument. While useful, currying doesn't fit well in TypeScript, especially **auto-currying** (see [a discussion about TypeScript support in Ramda’s repository](https://github.com/ramda/ramda/issues/2976#issuecomment-706475091)). It’s also quite challenging to create a type-safe, general-purpose `curry` function that works well with generics.\n\nHowever, it _is_ possible to create type-safe curry functions for a specific number of arguments (e.g., `curry2`, `curry3`, etc.), or use overloads for each number of arguments to create a close-to-general-purpose, type-safe `curry` function. hkt-core provides a utility called `Curry` that supports up to **3** arguments, which can be thought of as a combination of overloads for `curry2` and `curry3`.\n\nFor example, you can curry the previously defined `Map` function like this:\n\n```typescript\ntype CurriedMap = Curry\u003cMap\u003e;\ntype CurriedMapSig = Sig\u003cCurriedMap\u003e; // =\u003e \u003cT, U\u003e(f: (x: T) =\u003e U) =\u003e (xs: T[]) =\u003e U[]\ntype _ = Call1\u003cCall1\u003cCurriedMap, Append\u003c\"baz\"\u003e\u003e, [\"foo\", \"bar\"]\u003e; // =\u003e [\"foobaz\", \"barbaz\"]\n```\n\nYou can also create a curried version of `Reduce`:\n\n```typescript\ninterface Reduce extends TypeLambdaG\u003c[\"T\", \"U\"]\u003e {\n  signature: (\n    f: TypeLambda\u003c[acc: TArg\u003cthis, \"U\"\u003e, x: TArg\u003cthis, \"T\"\u003e], TArg\u003cthis, \"U\"\u003e\u003e,\n    init: TArg\u003cthis, \"U\"\u003e,\n    xs: TArg\u003cthis, \"T\"\u003e[],\n  ) =\u003e TArg\u003cthis, \"U\"\u003e;\n  return: _Reduce\u003cArg0\u003cthis\u003e, Arg1\u003cthis\u003e, Arg2\u003cthis\u003e\u003e;\n}\ntype ReduceSig = Sig\u003cReduce\u003e; // =\u003e \u003cT, U\u003e(f: (acc: U, x: T) =\u003e U, init: U, xs: T[]) =\u003e U\ntype _1 = Call3\u003cReduce, Concat, \"\", [\"foo\", \"bar\", \"baz\"]\u003e; // =\u003e \"foobarbaz\"\n\ntype CurriedReduce = Curry\u003cReduce\u003e;\ntype CurriedReduceSig = Sig\u003cCurriedReduce\u003e; // =\u003e \u003cT, U\u003e(f: (acc: U, x: T) =\u003e U) =\u003e (init: U) =\u003e (xs: T[]) =\u003e U\ntype _2 = Call1\u003cCall1\u003cCall1\u003cCurriedReduce, Concat\u003e, \"\"\u003e, [\"foo\", \"bar\", \"baz\"]\u003e; // =\u003e \"foobarbaz\"\n```\n\n`Curry` is also quite useful in combination with `Flip`. If you have a binary type-level function like `Map`, you can use `Curry` and `Flip` to create two type-level function templates with different argument orders:\n\n```typescript\n// \u003cT, U\u003e[f: (x: T) =\u003e U](xs: T[]) =\u003e U[]\ntype MapBy\u003cF extends TypeLambda1\u003e = Call1\u003cCurry\u003cMap\u003e, F\u003e;\ntype MapBySig = Sig\u003cMapBy\u003cAppend\u003c\"baz\"\u003e\u003e\u003e; // =\u003e (xs: string[]) =\u003e string[]\n\n// \u003cT, U\u003e[xs: T[]](f: (x: T) =\u003e U) =\u003e U[]\ntype MapOn\u003cTS extends unknown[]\u003e = Call1\u003cCurry\u003cFlip\u003cMap\u003e\u003e, TS\u003e;\ntype MapOnSig = Sig\u003cMapOn\u003cstring[]\u003e\u003e; // =\u003e (f: (x: string) =\u003e unknown) =\u003e unknown[]\n```\n\nIt’s worth noting that `U` is widened to `unknown` in the `MapOn` example. This is a limitation of TypeScript’s type inference system, and you’ll encounter the same issue if you define similar non-type-level `flip` and `curry2` functions in TypeScript. We provide this example for demonstration purposes, but in real-world scenarios, manually creating curried versions for the two different argument orders is generally a better choice.\n\n### Tips for creating and managing your type-level functions\n\nhkt-core is a _core_ library that provides essential utilities for type-level programming in TypeScript, but it doesn’t come with many built-in type-level functions out of the box. We’ve shown some examples of useful type-level functions in the previous sections, and you might create your own toolkit with a lot of useful type-level functions based on hkt-core. Below are some tips for creating and managing your type-level functions effectively.\n\nFirst, while it might seem appealing, we don’t recommend creating auto-currying type-level functions like those in [HOTScript](https://github.com/gvergnaud/HOTScript). TypeScript cannot reliably identify whether a function is partially applied or not (see [a discussion about TypeScript support in Ramda’s repository](https://github.com/ramda/ramda/issues/2976#issuecomment-706475091)), and this applies to type-level functions as well. Instead, we recommend manually creating curried functions, similar to how [Effect](https://github.com/Effect-TS/effect) and [fp-ts](https://github.com/gcanti/fp-ts) handles currying.\n\nAnother challenge is how to manage different variants of the same type-level function — such as the simple generic version, the type-level function version, and the type-level function template version. A useful strategy is to apply different suffixes to distinguish between these variants. For example, `Map`, `Map$`, and `Map$$`, where the number of `$` indicates the number of arguments the returned type-level function accepts:\n\n```typescript\ntype ConcatNames\u003cNames extends string[]\u003e = Pipe\u003c\n  Names,\n  List.Filter$\u003cFlow\u003cStr.Length$, Any.NotExtend$\u003c1 | 2\u003e\u003e\u003e,\n  List.Map$\u003cStr.Cap$\u003e,\n  List.Join$\u003c\", \"\u003e\n\u003e;\n\nexport namespace Any {\n  /* NotExtend */\n  export type NotExtend\u003cT, U\u003e = [T] extends [U] ? false : true;\n  export interface NotExtend$\u003cU\u003e extends TypeLambda\u003c[x: unknown], boolean\u003e {\n    return: NotExtend\u003cArg0\u003cthis\u003e, U\u003e;\n  }\n  export interface NotExtend$$ extends TypeLambda\u003c[x: unknown, y: unknown], boolean\u003e {\n    return: NotExtend\u003cArg0\u003cthis\u003e, Arg1\u003cthis\u003e\u003e;\n  }\n}\n\nexport namespace List {\n  /* Filter */\n  export type Filter\u003cF extends TypeLambda1\u003cTS[number], boolean\u003e, TS extends unknown[]\u003e = _Filter\u003c\n    F,\n    TS\n  \u003e;\n  type _Filter\u003cF, TS, Acc extends unknown[] = []\u003e =\n    TS extends [infer Head, ...infer Tail] ?\n      Call1W\u003cF, Head\u003e extends true ?\n        _Filter\u003cF, Tail, [...Acc, Head]\u003e\n      : _Filter\u003cF, Tail, Acc\u003e\n    : Acc;\n  export interface Filter$\u003cF extends TypeLambda1\u003cnever, boolean\u003e\u003e\n    extends TypeLambda\u003c[xs: Param0\u003cF\u003e[]], Param0\u003cF\u003e[]\u003e {\n    return: _Filter\u003cF, Arg0\u003cthis\u003e\u003e;\n  }\n  export interface Filter$$ extends TypeLambdaG\u003c[\"T\"]\u003e {\n    signature: (\n      f: TypeLambda\u003c[x: TArg\u003cthis, \"T\"\u003e], boolean\u003e,\n      xs: TArg\u003cthis, \"T\"\u003e[],\n    ) =\u003e TArg\u003cthis, \"T\"\u003e[];\n    return: _Filter\u003cArg0\u003cthis\u003e, Arg1\u003cthis\u003e\u003e;\n  }\n\n  /* Map */\n  export type Map\u003cF extends TypeLambda1\u003cTS[number]\u003e, TS extends unknown[]\u003e = _Map\u003cF, TS\u003e;\n  type _Map\u003cF, TS\u003e = { [K in keyof TS]: Call1W\u003cF, TS[K]\u003e };\n  export interface Map$\u003cF extends TypeLambda1\u003e extends TypeLambda\u003c[xs: Param0\u003cF\u003e[]], RetType\u003cF\u003e[]\u003e {\n    return: _Map\u003cF, Arg0\u003cthis\u003e\u003e;\n  }\n  export interface Map$$ extends TypeLambdaG\u003c[\"T\", \"U\"]\u003e {\n    signature: (\n      f: TypeLambda\u003c[x: TArg\u003cthis, \"T\"\u003e], TArg\u003cthis, \"U\"\u003e\u003e,\n      xs: TArg\u003cthis, \"T\"\u003e[],\n    ) =\u003e TArg\u003cthis, \"U\"\u003e[];\n    return: _Map\u003cArg0\u003cthis\u003e, Arg1\u003cthis\u003e\u003e;\n  }\n\n  /* Reduce */\n  export type Reduce\u003c\n    F extends TypeLambda2\u003cnever, TS[number]\u003e,\n    Init extends Param0\u003cF\u003e,\n    TS extends unknown[],\n  \u003e = _Reduce\u003cF, TS, Init\u003e;\n  type _Reduce\u003cF, TS, Acc\u003e =\n    TS extends [infer Head, ...infer Tail] ? _Reduce\u003cF, Tail, Call2W\u003cF, Acc, Head\u003e\u003e : Acc;\n  export interface Reduce$\u003cF extends TypeLambda2, Init extends Param0\u003cF\u003e\u003e\n    extends TypeLambda\u003c[xs: Param1\u003cF\u003e[]], Param0\u003cF\u003e\u003e {\n    return: _Reduce\u003cF, Arg0\u003cthis\u003e, Init\u003e;\n  }\n  export interface Reduce$$$ extends TypeLambdaG\u003c[\"T\", \"U\"]\u003e {\n    signature: (\n      f: TypeLambda\u003c[acc: TArg\u003cthis, \"U\"\u003e, x: TArg\u003cthis, \"T\"\u003e], TArg\u003cthis, \"U\"\u003e\u003e,\n      init: TArg\u003cthis, \"U\"\u003e,\n      xs: TArg\u003cthis, \"T\"\u003e[],\n    ) =\u003e TArg\u003cthis, \"U\"\u003e;\n    return: _Reduce\u003cArg0\u003cthis\u003e, Arg2\u003cthis\u003e, Arg1\u003cthis\u003e\u003e;\n  }\n\n  /* Join */\n  export type Join\u003cSep extends string, Strings extends string[]\u003e = _Join\u003cSep, Strings\u003e;\n  type _Join\u003cSep extends string, Strings extends string[], Acc extends string = \"\"\u003e =\n    Strings extends [infer Head extends string, ...infer Tail extends string[]] ?\n      _Join\u003cSep, Tail, `${Acc}${Acc extends \"\" ? \"\" : Sep}${Head}`\u003e\n    : Acc;\n  export interface Join$\u003cSep extends string\u003e extends TypeLambda\u003c[ss: string[]], string\u003e {\n    return: _Join\u003cSep, Arg0\u003cthis\u003e\u003e;\n  }\n  export interface Join$$ extends TypeLambda\u003c[sep: string, strings: string[]], string\u003e {\n    return: _Join\u003cArg0\u003cthis\u003e, Arg1\u003cthis\u003e\u003e;\n  }\n}\n\nexport namespace Str {\n  /* Cap */\n  export type Cap\u003cS extends string\u003e = Capitalize\u003cS\u003e;\n  export interface Cap$ extends TypeLambda\u003c[s: string], string\u003e {\n    return: Cap\u003cArg0\u003cthis\u003e\u003e;\n  }\n\n  /* Length */\n  export type Length\u003cS extends string\u003e = _Length\u003cS\u003e;\n  type _Length\u003cS extends string, Acc extends void[] = []\u003e =\n    S extends `${string}${infer Tail}` ? _Length\u003cTail, [...Acc, void]\u003e : Acc[\"length\"];\n  export interface Length$ extends TypeLambda\u003c[s: string], number\u003e {\n    return: _Length\u003cArg0\u003cthis\u003e\u003e;\n  }\n}\n```\n\nWe use namespaces here to avoid polluting the global scope, and apply different suffixes to distinguish different variants of the same type-level function. For instance, `List.Map` is a simple generic type that isn’t a type-level function, `List.Map$` is a type-level function template that accepts a single argument, and `List.Map$$` is a type-level function that accepts two arguments. This naming convention allows you to easily manage various versions of the same type-level function and avoid confusion.\n\n### Performance\n\nFor experienced TypeScript developers, performance in type-level programming is a common concern. Although hkt-core uses many conditional types and recursive type aliases, it’s designed so that TypeScript simplifies types as if hkt-core weren’t even there. For example:\n\n```typescript\nimport type { Arg0, Pipe, TypeLambda } from \"hkt-core\";\n\ninterface CapStr extends TypeLambda\u003c[s: string], string\u003e {\n  return: Capitalize\u003cArg0\u003cthis\u003e\u003e;\n}\n\ninterface StrLength extends TypeLambda\u003c[s: string], number\u003e {\n  return: _StrLength\u003cArg0\u003cthis\u003e\u003e;\n}\ntype _StrLength\u003cS extends string, Acc extends void[] = []\u003e =\n  S extends `${string}${infer Tail}` ? _StrLength\u003cTail, [...Acc, void]\u003e : Acc[\"length\"];\n\ntype F\u003cS extends string\u003e = Pipe\u003cS, CapStr, StrLength\u003e;\n```\n\nWhen you hover over `F`, TypeScript simplifies it to something like:\n\n```typescript\ntype F\u003cS extends string\u003e =\n  Capitalize\u003cS\u003e extends `${string}${infer Tail}` ? _StrLength\u003cTail, [void]\u003e : 0;\n```\n\nThis is equivalent to writing the type directly without hkt-core, demonstrating that the extra type-checking adds minimal overhead.\n\nHowever, there are cases where hkt-core can slow down the TypeScript compiler, especially when using utilities with _type validation_ (not merely _type checking_) features. In particular, `Apply` and its variants might slow down the compiler when used with _generic_ type-level functions that have complex type signatures — if you encounter this, try using `ApplyW` and `Call*W` instead. On the other hand, even though `Args` and its variants also perform type validation, they seldom affect the compiler’s performance, so normally, you can safely use them without worry.\n\n## FAQ\n\n### Should I add it as a dev dependency or a regular dependency?\n\nEven though hkt-core is a type-only library, it **should _not_** be added as a dev dependency if you are developing a library or framework that will be used by other projects. Without hkt-core as a regular dependency, the type definitions of your library will be incomplete, and users will encounter type errors when they try to use it.\n\nOn the other hand, if you’re using hkt-core just for your own project and don’t plan to publish it as a library, you can safely add it as a dev dependency.\n\n### _Generic_ type-level functions don’t infer types correctly!\n\nhkt-core simulates the TypeScript type system at the type level as closely as possible, but it’s not perfect. If something doesn’t work in TypeScript, it’s likely that it won’t work in hkt-core either. When encountering issues with generic type-level functions, first test whether their equivalent runtime version works in TypeScript (you can use Effect or other libraries for this). If it doesn’t work in TypeScript, it’s also unlikely to work in hkt-core.\n\nFor example, the following code will trigger an error in TypeScript:\n\n```typescript\ninterface Head extends TypeLambdaG\u003c[\"T\"]\u003e {\n  signature: (tuple: [TArg\u003cthis, \"T\"\u003e, ...unknown[]]) =\u003e TArg\u003cthis, \"T\"\u003e;\n  return: Arg0\u003cthis\u003e[0];\n}\n\ntype Composed = Flow\u003cHead, Head, Head\u003e;\n//                         ~~~~\n// Type 'Head' does not satisfy the constraint 'TypeLambda1\u003cunknown, any\u003e'.\n//   Types of property 'signature' are incompatible.\n//     Type '(tuple: [unknown, ...unknown[]]) =\u003e unknown' is not assignable to type '(args_0: unknown) =\u003e any'.\n//       Types of parameters 'tuple' and 'args_0' are incompatible.\n//         Type 'unknown' is not assignable to type '[unknown, ...unknown[]]'.\n```\n\nYou might expect the signature of `Composed` to be inferred as `\u003cT\u003e(tuple3: [[[T, ...unknown[]], ...unknown[]], ...unknown[]]) =\u003e T`, but this is the expected behavior. If you try the equivalent runtime code in Effect, you’ll see that it still doesn’t work in TypeScript:\n\n```typescript\nimport { flow } from \"effect\";\n\nconst head = \u003cT\u003e(tuple: [T, ...unknown[]]): T =\u003e tuple[0];\n\nflow(head, head, head);\n//   ~~~~\n// Argument of type '\u003cT\u003e(tuple: [T, ...unknown[]]) =\u003e T' is not assignable to parameter of type '(tuple: [T, ...unknown[]]) =\u003e [unknown, ...unknown[]]'.\n//   Type 'T' is not assignable to type '[unknown, ...unknown[]]'.\n```\n\nThese kinds of “issues” are not considered bugs in hkt-core. In such cases, it’s often necessary to rethink your design and simplify the type-level functions to avoid complex type inference issues.\n\nThough many unexpected behaviors are _not_ true issues, as described above, there are also cases where unexpected behavior is due to **limitations** inherent in hkt-core, particularly with generic function composition. For example, the following code works in TypeScript because TypeScript provides special support for generic function types:\n\n```typescript\ndeclare function compose2\u003cT, U, V\u003e(g: (y: U) =\u003e V, f: (x: T) =\u003e U): (x: T) =\u003e V;\n\ndeclare function toString(n: number): string;\ndeclare function makeTuple\u003cT\u003e(x: T): [T];\n\nconst testCompose2 = compose2(makeTuple, toString);\n//    ^?: (x: number) =\u003e [string]\n```\n\nHowever, if you try to define a similar type-level `Compose2` in hkt-core, it won’t work as expected:\n\n```typescript\ninterface Compose2 extends TypeLambdaG\u003c[\"T\", \"U\", \"V\"]\u003e {\n  signature: (\n    g: (y: TArg\u003cthis, \"U\"\u003e) =\u003e TArg\u003cthis, \"V\"\u003e,\n    f: (x: TArg\u003cthis, \"T\"\u003e) =\u003e TArg\u003cthis, \"U\"\u003e,\n  ) =\u003e (x: TArg\u003cthis, \"T\"\u003e) =\u003e TArg\u003cthis, \"V\"\u003e;\n}\n\ndeclare function toString(n: number): string;\ndeclare function makeTuple\u003cT\u003e(x: T): [T];\n\ntype TestCompose2 = RetType\u003cCompose2, [typeof makeTuple, typeof toString]\u003e; // =\u003e (x: number) =\u003e [unknown]\n```\n\nHere, the return type is inferred as `(x: number) =\u003e [unknown]` instead of `(x: number) =\u003e [string]`. Since hkt-core simulates the TypeScript type system at the type level, it cannot provide the same special support for generic function types that TypeScript does.\n\nWhile these limitations are not expected to be fixed in the near future, you’re welcome to open an issue to present these cases and discuss potential solutions.\n\nIf you believe you’ve encountered a bug — where the equivalent runtime code works in TypeScript but hkt-core behaves unexpectedly — please [open an issue on the GitHub repository](https://www.github.com/Snowflyt/hkt-core/issues) with a minimal reproduction case. Some known issues are already listed there, so please check whether your issue has already been reported before submitting a new one.\n\n### What’s the magic behind generic type-level functions?\n\nHere’s a minimal example of a generic type-level function:\n\n```typescript\ntype TODO = any;\n\n// Utility types for type arguments\ntype ArgT\u003cF\u003e = F extends { T: infer T } ? T : never;\ntype ArgU\u003cF\u003e = F extends { U: infer U } ? U : never;\n\n// Define a generic type-level function\ninterface Map {\n  signature: (f: (x: ArgT\u003cthis\u003e) =\u003e ArgU\u003cthis\u003e, xs: ArgT\u003cthis\u003e[]) =\u003e ArgU\u003cthis\u003e[];\n  return: TODO;\n}\n\n// Instantiate type arguments from known parameter types\ntype TypeArgs =\n  // ^?: { T: string; U: number }\n  ((f: (x: string) =\u003e number, xs: string[]) =\u003e never) extends (\n    (Map \u0026 { T: infer T; U: infer U })[\"signature\"]\n  ) ?\n    { T: T; U: U }\n  : never;\n\n// Get the refined signature with instantiated type args\ntype _ = (Map \u0026 TypeArgs)[\"signature\"];\n//   ^?: (f: (x: string) =\u003e number, xs: string[]) =\u003e number[]\n```\n\nWe use `ArgT` and `ArgU` to extract the type arguments from the type-level function, just like `TArg` in hkt-core. We then instantiate the type arguments from known parameter types and refine the signature with the instantiated type arguments. This is the basic idea behind generic type-level functions.\n\nWe use `ArgT` and `ArgU` to extract the type arguments from the type-level function — just like `TArg` in hkt-core. Then we instantiate these type arguments from known parameter types and refine the signature accordingly. This is the core idea behind generic type-level functions.\n\nWhile the example above works well for simple cases, it doesn’t handle subtyping correctly. For instance, the following code will simply yield never:\n\n```typescript\n// We replace `xs: string[]` with `xs: \"foo\"[]` to test subtyping\ntype TypeArgs =\n  // ^?: never\n  ((f: (x: string) =\u003e number, xs: \"foo\"[]) =\u003e never) extends (\n    (Map \u0026 { T: infer T; U: infer U })[\"signature\"]\n  ) ?\n    { T: T; U: U }\n  : never;\n```\n\nTo support subtyping properly, we need to **flip the variance** of parameter types in our type-level function. We achieve this by wrapping each parameter with a helper type that inverts the variance:\n\n```typescript\n// Flip the variance of a type\ninterface In\u003cT\u003e {\n  (_: T): void;\n}\n\n// Same as before\ntype ArgT\u003cF\u003e = F extends { T: infer T } ? T : never;\ntype ArgU\u003cF\u003e = F extends { U: infer U } ? U : never;\n\n// Wrap each parameter with `In\u003c...\u003e`\ninterface Map {\n  signature: (f: In\u003c(x: ArgT\u003cthis\u003e) =\u003e ArgU\u003cthis\u003e\u003e, xs: In\u003cArgT\u003cthis\u003e[]\u003e) =\u003e ArgU\u003cthis\u003e[];\n  return: any;\n}\n\n// Still wrap each parameter with `In\u003c...\u003e`, and...\n// Now it works!\ntype TypeArgs =\n  // ^?: { T: \"foo\"; U: number }\n  ((f: In\u003c(x: string) =\u003e number\u003e, xs: In\u003c\"foo\"[]\u003e) =\u003e never) extends (\n    (Map \u0026 { T: infer T; U: infer U })[\"signature\"]\n  ) ?\n    { T: T; U: U }\n  : never;\n\ntype _ = (Map \u0026 TypeArgs)[\"signature\"];\n//   ^?: (f: In\u003c(x: \"foo\") =\u003e number\u003e, xs: In\u003c\"foo\"[]\u003e) =\u003e number[\n```\n\nThis might seem like magic at first, and it can be a bit tricky to grasp initially. We’ll skip the finer details here, but if you’re curious, you can apply the variance rules in TypeScript step by step to see how everything falls into place.\n\nInternally, hkt-core uses a similar technique to handle variance correctly, so you don’t have to write this kind of code yourself. Understanding the basic idea behind generic type-level functions can help explain why some seemingly simple functions might not infer types correctly in edge cases.\n\n### Why not just access arguments and type parameters via `this`?\n\nLibraries like [HOTScript](https://github.com/gvergnaud/hotscript) use syntax like `this[\"arg0\"]` to access arguments inside a type-level function. While this approach seems simpler and more concise, it introduces unnecessary properties to the type-level function, which can lead to variance issues. Let’s first revisit the variance of function types in TypeScript:\n\n```typescript\ntype IsSubtype\u003cT, U\u003e = [T] extends [U] ? true : false;\n\n// All types are subtypes of `unknown`\ntype Test1 = IsSubtype\u003cstring, unknown\u003e; // =\u003e true\n// `never` is the subtype of all types\ntype Test2 = IsSubtype\u003cnever, string\u003e; // =\u003e true\n\n// `() =\u003e string` is also a subtype of `() =\u003e unknown`,\n// indicating the return type of a function is covariant\ntype TestReturn = IsSubtype\u003c() =\u003e string, () =\u003e unknown\u003e; // =\u003e true\n// While `(_: string) =\u003e void` is not a subtype of `(_: unknown) =\u003e void`,\n// instead, `(_: unknown) =\u003e void` is a subtype of `(_: string) =\u003e void`,\n// indicating the parameter type of a function is contravariant\ntype TestParam1 = IsSubtype\u003c(_: string) =\u003e void, (_: unknown) =\u003e void\u003e; // =\u003e false\ntype TestParam2 = IsSubtype\u003c(_: unknown) =\u003e void, (_: string) =\u003e void\u003e; // =\u003e true\n\n// So we get the following result\ntype TestFunc = IsSubtype\u003c(_: string) =\u003e number, (_: never) =\u003e unknown\u003e; // =\u003e true\n```\n\nhkt-core provides a _typed_ version of type-level functions, so we should keep the variance rules of `TypeLambda` aligned with TypeScript’s function types. However, if we add extra properties like `args` to `TypeLambda` for convenience to access arguments, we can break the variance rules:\n\n```typescript\ninterface TypeLambda\u003cParams extends unknown[], R\u003e {\n  signature: (...args: Params) =\u003e R;\n  args: Params;\n}\n\n// Oops! This _should_ be `true` as expected\ntype TestVariance = IsSubtype\u003cTypeLambda\u003c[string], number\u003e, TypeLambda\u003c[never], unknown\u003e\u003e; // =\u003e false\n```\n\nIf we remove the `args: Params` from the code above, we get the standard `TypeLambda` implementation as it is defined in `hkt-core`, and the result of `TestVariance` will be `true` as expected. However, by adding `args: Params` back, `Params` now appears in both a contravariant position (as function parameters in the `signature` property) and a covariant position (as the `args` property). This makes `Params` invariant and breaks the variance rules.\n\nNow, you might wonder, what if we use a contravariant **`args`** property, like `args: (_: Params) =\u003e void`? While this would work, it forces the user to access the arguments using the more complex syntax `Parameters\u003cthis[\"args\"]\u003e[0]`, which doesn’t provide much benefit over the standard **`Args`** utility in **hkt-core**.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsnowflyt%2Fhkt-core","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsnowflyt%2Fhkt-core","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsnowflyt%2Fhkt-core/lists"}