如何设置构造函数中未知的打字稿成员变量

how to set typescript member variables that are unknown in constructor

我正在学习 Typescript,想知道如何正确定义 class 成员变量。

目前,我在构造函数上方的 class 中声明它们,但为了确保它们在构造函数中实例化(或者我收到警告),我将它们声明为什么类型 |无效的。 这意味着如果我可以在构造函数中实例化成员变量,方法是将其设置为 null,然后在我能够时将其设置为适当的值。

我不知道这是声明成员变量的正确方法。 例如:

export default class FlowerBed {
  canv:HTMLCanvasElement | null;
  ctx:CanvasRenderingContext2D | null;
  p2d:Path2D;
  t:number;
  currentPoint:Array<number>;
  to:number = 0;
  image:HTMLImageElement | null;
  imagesrc:CanvasImageSource | null;
  pattern:CanvasPattern | null;

  constructor (garden:HTMLCanvasElement) {
    this.image = null;
    this.imagesrc = null;
    this.canv = null;
    this.ctx = null;
    this.pattern = null;
    this.to = 0;
    this.p2d = new Path2D();
    this.t = 0;
    this.currentPoint = [160,350];  
  }

我在构建的时候没有canvas,ctx,pattern等值

有没有更正确的处理方式?

非常感谢...

因此,如果您不需要使用具有特殊含义的 null,您可以简化您的 class

export default class FlowerBed {
  canv?: HTMLCanvasElement;
  ctx?: CanvasRenderingContext2D;
  p2d: Path2D = new Path2D();
  t: number = 0;
  currentPoint: Array<number> = [160, 350];
  to: number = 0;
  image?: HTMLImageElement;
  imagesrc?: CanvasImageSource;
  pattern?: CanvasPattern;

  constructor(garden: HTMLCanvasElement) {
    // ...
  }

  someMethod() {
    // Note the exclamation mark – it tells ts you are sure the property has a value
    return this.canv!.getBoundingClientRect();
  }
}

? 字段名后表示该字段可以缺少什么和有它几乎一样undefined。根据您的经验,您可能更愿意将值分配给构造函数,但您仍然可以在这里避免空分配。

值得注意的是对象中不存在未初始化的属性,因此运行时检查如 hasOwnProperty return false.

const fb = new FlowerBed(canvasEl);
fb.hasOwnProperty('ctx'); // false

因此,如果这很重要,您可以初始化它们,但不必在构造函数中进行初始化。

export default class FlowerBed {
  canv?: HTMLCanvasElement;
  ctx?: CanvasRenderingContext2D = undefined;
  // ...
}

当 属性 可能在运行时获得一些无效值时,这可能很有用,这是一些开发人员区分 undefinednull 值的原因之一, 使用 undefined 作为 "not yet initialized" 和 null 作为 "empty or non-existent value"