Builder pattern using TypeScript interfaces

后端 未结 3 1026
慢半拍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条回答
  •  盖世英雄少女心
    2020-12-18 08:48

    Based on the previous answers I wrote a generic Typescript builder which provides:

    • Type-Safety
    • Differentiation of optional and required properties
    • Generic method (with) for adding parts of the object
    • Validation of the object before creating it
    • Domain Driven Design conformity (no need to specify methods when using Builder)

    If you are interested, you can find further information and examples here: https://github.com/hanterlantant/ts-generic-builder And the npm package here: https://www.npmjs.com/package/ts-generic-builder

提交回复
热议问题