Builder pattern using TypeScript interfaces

后端 未结 3 1021
慢半拍i
慢半拍i 2020-12-18 08:39

I would like to do something like this:

interface IPoint {
    x : number;
    y : number;
    z? : number;
}
const diag : IPoint = IPoint.x(1)
                      


        
3条回答
  •  Happy的楠姐
    2020-12-18 08:59

    This handles the type:

    interface IPoint {
        x: number;
        y: number;
        z?: number;
    }
    
    type IBuilder = {
        [k in keyof T]: (arg: T[k]) => IBuilder
    } & { build(): T }
    
    
    let builder = {} as IBuilder
    
    const diag = builder.x(1).y(2).z(undefined).build()
    

    But I don't know how will you create the actual Builder thou. :)

    You can play around with it at the playground

    EDIT: Vincent Peng has created a builder-pattern npm package our of this (as mentioned in the comment). Go and give it some love!

提交回复
热议问题