首页 > 解决方案 > 如何在 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,isThindoughType默认值,因为它似乎违背了构建器背后的想法。我不能将它们设置为undefined因为那不起作用。

有没有避免过度膨胀的解决方案?添加布尔值以检测是否已设置某些内容似乎是一场噩梦。

标签: typescriptbuilder

解决方案


TypeScript 抱怨是因为在严格模式下,undefined不能分配给 types numberboolean, or DoughType,并且在严格模式下,每个类属性都必须使用其类型的值进行初始化。

由于您的意思是这些属性可能未定义,因此您可以使用包含作为有效值的联合类型显式键入它们:undefined

private numberOfSlices: number | undefined;
private isThin: boolean | undefined;
private doughType: DoughType | undefined;
private toppings: Topping[] = [];

在 TypeScript 2.7 版本说明中有更多关于严格类初始化的信息。


推荐阅读