使用 TypeScript 接口的构建器模式 [英] Builder pattern using TypeScript interfaces

查看:24
本文介绍了使用 TypeScript 接口的构建器模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

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

我意识到我可以自己实现这一点,但想知道是否有一种自动的方法来做到这一点?给定的 TypeScript 已经知道类型信息.

I realize I could implement this myself, but was wondering if there was an automatic way to do this? given TypeScript already knows the type information.

我要求使用这种语法,因为我目前可以做到这一点.

I am requesting this kind of syntax because I can do this currently.

const diag : IPoint = {x: 1, y: 1};

推荐答案

这里处理的类型:

interface IPoint {
    x: number;
    y: number;
    z?: number;
}

type IBuilder<T> = {
    [k in keyof T]: (arg: T[k]) => IBuilder<T>
} & { build(): T }


let builder = {} as IBuilder<IPoint>

const diag = builder.x(1).y(2).z(undefined).build()

但我不知道你将如何创建实际的Builder.:)

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

您可以在 游乐场

Vincent Peng 创建了一个 builder-pattern npm 包(如评论中所述).去给它一些爱吧!

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

这篇关于使用 TypeScript 接口的构建器模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆