Skip to content

Instantly share code, notes, and snippets.

@bakerface
Last active June 27, 2021 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bakerface/eb582cb9e0b2045a2211a94b834c2be4 to your computer and use it in GitHub Desktop.
Save bakerface/eb582cb9e0b2045a2211a94b834c2be4 to your computer and use it in GitHub Desktop.
TypeScript helpers for fluent types.
import type { Fluent } from "./fluent";
export class User {
public id: string;
public username: string;
private constructor() {
this.id = "";
this.username = "";
}
static create(): Fluent<User> {
return new User();
}
withId(id: string): this {
this.id = id;
return this;
}
withUsername(username: string): this {
this.username = username;
return this;
}
}
export type Fluent<T, Keys extends keyof T = FluentKeys<T>> = {
[K in Keys]: ChangeReturn<
T[K],
Exclude<Keys, K> extends never ? T : Fluent<T, Exclude<Keys, K>>
>;
};
type FluentKeys<T> = {
[K in keyof T]: T[K] extends (...args: any[]) => T ? K : never;
}[keyof T];
type ChangeReturn<F, Return> = F extends (...args: infer Args) => any
? (...args: Args) => Return
: never;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment