Created
January 28, 2025 02:24
-
-
Save SuperCoolFrog/1c2e20e97a07f3c3c68d08c14be48461 to your computer and use it in GitHub Desktop.
Generic Builder Example - Not Tested
This file contains hidden or 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
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