Skip to content

Instantly share code, notes, and snippets.

@SuperCoolFrog
Created January 28, 2025 02:24
Show Gist options
  • Save SuperCoolFrog/1c2e20e97a07f3c3c68d08c14be48461 to your computer and use it in GitHub Desktop.
Save SuperCoolFrog/1c2e20e97a07f3c3c68d08c14be48461 to your computer and use it in GitHub Desktop.
Generic Builder Example - Not Tested
class Builder<T> {
private data: Partial<T> = {};
constructor(initialData?: Partial<T>) {
if (initialData) {
this.data = { ...initialData };
}
}
with<K extends keyof T>(key: K, value: T[K]): Builder<T> {
this.data[key] = value;
return this;
}
build(): T {
return this.data as T;
}
}
interface User {
name: string;
age: number;
email?: string;
}
const userBuilder = new Builder<User>();
const user = userBuilder
.with("name", "John")
.with("age", 30)
.with("email", "[email protected]")
.build();
console.log(user.name); // Autocomplete works for 'name', 'age', and 'email'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment