Last active
September 20, 2017 04:03
-
-
Save wonderful-panda/e104f21e751f30c7b231eb7c8e1d7de3 to your computer and use it in GitHub Desktop.
TypeSafeなbuilder (see https://gist.github.com/wreulicke/e45c3eb093acfd489708ffccee15636e)
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
| type DiffKey<T extends string, U extends string> = ( | |
| & {[P in T]: P } | |
| & {[P in U]: never } | |
| & { [x: string]: never } | |
| )[T]; | |
| type Omit<T, K extends keyof T> = Pick<T, DiffKey<keyof T, K>>; | |
| type Diff<T, U> = Omit<T, keyof U & keyof T>; | |
| type Builder<T> = { | |
| [K in keyof T]: (arg: T[K]) => Builder<Omit<T, K>>; | |
| } & { | |
| build(): string; | |
| } | |
| interface AllMembers { | |
| foo: string; | |
| bar: number; | |
| baz: boolean; | |
| } | |
| class BuilderImpl { | |
| constructor(public text: string) { | |
| } | |
| foo(arg: string) { | |
| return new BuilderImpl(this.text + `foo(${arg}), `); | |
| } | |
| bar(arg: number) { | |
| return new BuilderImpl(this.text + `bar(${arg}), `); | |
| } | |
| baz(arg: boolean) { | |
| return new BuilderImpl(this.text + `baz(${arg}), `); | |
| } | |
| build() { | |
| return this.text; | |
| } | |
| } | |
| const builder: Builder<AllMembers> = new BuilderImpl(""); | |
| console.log(builder.bar(1).baz(true).foo("hoge").build()); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
無駄なところがあったので修正したらほぼwなんとかさんの例と同じになった