Last active
June 27, 2021 18:18
-
-
Save bakerface/eb582cb9e0b2045a2211a94b834c2be4 to your computer and use it in GitHub Desktop.
TypeScript helpers for fluent types.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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