typescript - 如何在 TypeScript 严格模式下键入此对象构建器而不使其膨胀?
问题描述
我喜欢我在网上找到的这个构建器模式,但在严格模式下它不起作用,因为前 3 个属性与第一个属性相同:
(property) PizzaBuilder.numberOfSlices: number
Property 'numberOfSlices' has no initializer and is not definitely assigned in the constructor.ts(2564)
export enum DoughType {
HEALTHY,
}
export enum Topping {
CHEESE,
}
export interface Pizza {
numberOfSlices: number;
isThin: boolean;
doughType: DoughType;
toppings: Topping[];
}
export class PizzaBuilder {
private numberOfSlices: number;
private isThin: boolean;
private doughType: DoughType;
private toppings: Topping[] = [];
public setNumberOfSlices(numberOfSlices: number): PizzaBuilder {
this.numberOfSlices = numberOfSlices;
return this;
}
public setIsThin(isThin: boolean): PizzaBuilder {
this.isThin = isThin;
return this;
}
public setDoughType(doughType: DoughType): PizzaBuilder {
this.doughType = doughType;
return this;
}
public addTopping(topping: Topping): PizzaBuilder {
this.toppings.push(topping);
return this;
}
public build(): Pizza {
if (this.isThin === undefined) this.isThin = false;
if (this.numberOfSlices === undefined) this.numberOfSlices = 8;
if (this.doughType === undefined) throw new Error('Dough type must be set');
if (this.toppings.length < 1) this.toppings.push(Topping.CHEESE);
return {
numberOfSlices: this.numberOfSlices,
isThin: this.isThin,
toppings: this.toppings,
doughType: this.doughType,
};
}
}
const pizza = new PizzaBuilder()
.setIsThin(true)
.setNumberOfSlices(6)
.setDoughType(DoughType.HEALTHY)
.addTopping(Topping.CHEESE)
.build();
我想避免给出numberOfSlices
,isThin
和doughType
默认值,因为它似乎违背了构建器背后的想法。我不能将它们设置为undefined
因为那不起作用。
有没有避免过度膨胀的解决方案?添加布尔值以检测是否已设置某些内容似乎是一场噩梦。
解决方案
TypeScript 抱怨是因为在严格模式下,undefined
不能分配给 types number
,boolean
, or DoughType
,并且在严格模式下,每个类属性都必须使用其类型的值进行初始化。
由于您的意思是这些属性可能未定义,因此您可以使用包含作为有效值的联合类型显式键入它们:undefined
private numberOfSlices: number | undefined;
private isThin: boolean | undefined;
private doughType: DoughType | undefined;
private toppings: Topping[] = [];
在 TypeScript 2.7 版本说明中有更多关于严格类初始化的信息。
推荐阅读
- python - 我正在尝试在 heroku 上托管 discord.py 机器人并且发生此错误
- javascript - javascript 字符串中 %1$s 的意义/目的?
- xcode - SwiftUI - 在滚动视图中使用 vstack 时导航栏标题动画错误
- rxjs - 如何使用 RxJs 使用多个异步任务来管道和调整批量操作?
- networking - 在终端本身中添加多个终端命令生成的值
- visual-studio-code - VS Code 自定义标签颜色
- c# - EF Core 3.1:我不理解脚手架代码中的配置错误
- algorithm - 切片神奇地更新
- c - 在 C 中,我的 execl 函数有效,但是在尝试使用 execlp 时,我没有从文件中得到任何打印
- reactjs - 你如何将道具传递到 reactjs 中的侧导航抽屉中?