Skip to content

Instantly share code, notes, and snippets.

@albertywu
Created February 24, 2019 06:43
Show Gist options
  • Select an option

  • Save albertywu/fa82ada6181224f66dcc83562ff72d87 to your computer and use it in GitHub Desktop.

Select an option

Save albertywu/fa82ada6181224f66dcc83562ff72d87 to your computer and use it in GitHub Desktop.
Builder Pattern (Typescript)
type Methods = 'get' | 'post';
interface Req {
data: object;
method: Methods;
url: string;
foo?: number
}
class Req implements Req {
constructor(req: Req) {
Object.assign(this, req);
}
}
class ReqBuilder implements Partial<Req> {
data?: object;
method?: Methods;
url?: string;
foo?: number
setData(data: object): this & Pick<Req, 'data'> {
return Object.assign(this, { data })
}
setMethod(method: Methods): this & Pick<Req, 'method'> {
return Object.assign(this, { method })
}
setUrl(url: string): this & Pick<Req, 'url'> {
return Object.assign(this, { url })
}
setFoo(foo: number): this & Required<Pick<Req, 'foo'>> {
return Object.assign(this, { foo })
}
build(this: Req) {
return new Req(this)
}
}
// works
new ReqBuilder()
.setData({})
.setMethod('post')
.setUrl('bar')
.build()
// works with optional setFoo
new ReqBuilder()
.setData({})
.setMethod('post')
.setUrl('bar')
.setFoo(42)
.build()
// can't call .build() unless required setters are called first
new ReqBuilder()
.setData({})
.build()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment