Skip to content

Instantly share code, notes, and snippets.

@ENvironmentSet
Last active September 11, 2024 20:01
Show Gist options
  • Save ENvironmentSet/1662a140f99381bc85fd6be51ecdcbb5 to your computer and use it in GitHub Desktop.
Save ENvironmentSet/1662a140f99381bc85fd6be51ecdcbb5 to your computer and use it in GitHub Desktop.
Encoding HKTs in typescript without declaration merging
export interface HKT {
param: unknown;
result: unknown;
}
interface NotHKT extends HKT {
result: this['param'] extends true ? false : true;
}
interface FstHKT extends HKT {
result: this['param'] extends [infer A, infer _] ? A : never;
}
interface ArrayHKT extends HKT {
result: Array<this['param']>;
}
export type Apply<f extends HKT, x>
= (f & { param: x })['result'];
type Test1 = Apply<NotHKT, true> // be deducedd to `false`
type Test2 = Apply<FstHKT, [string, boolean]> // be deduced to `string`
type Test3 = Apply<ArrayHKT, number> // be deduced to `number[]`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment