gpt4 book ai didi

typescript - 使用 TypeScript 接口(interface)的构建器模式

转载 作者:搜寻专家 更新时间:2023-10-30 21:02:16 25 4
gpt4 key购买 nike

我想做这样的事情:

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

我知道我可以自己实现这个,但想知道是否有一种自动方法可以做到这一点?假设 TypeScript 已经知道类型信息。

编辑:我要求这种语法,因为我目前可以做到这一点。

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

最佳答案

下面的设计通过完成三件事来增加类型安全:

  1. 它知道已经提供了哪些必需的属性。
  2. 它知道已经提供了哪些可选属性。
  3. 只有在您提供了所有必需的属性后,才会让您构建

本身:

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

class Point implements Point {
constructor(point: Point) {
Object.assign(this, point);
}
}

Point 生成器:

class PointBuilder implements Partial<Point> {
x?: number;
y?: number;
z?: number;

withX(value: number): this & Pick<Point, 'x'> {
return Object.assign(this, { x: value });
}

withY(value: number): this & Pick<Point, 'y'> {
return Object.assign(this, { y: value });
}

withZ(value: number): this & Required<Pick<Point, 'z'>> {
return Object.assign(this, { z: value });
}

build(this: Point) {
return new Point(this);
}
}

用法:

/**
* The `z` property is optional.
*/
new PointBuilder()
.withX(1)
.withY(1)
.build();

/**
* The `.build()` method cannot be called — we are still missing `y`.
*/
new PointBuilder()
.withX(1)
.withZ(1);

/**
* The `z` property is correctly recognized as `number` (as opposed to `number | undefined`).
*/
new PointBuilder()
.withX(1)
.withZ(1)
.z

关于typescript - 使用 TypeScript 接口(interface)的构建器模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45291644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com