打字稿:和!在课程属性中

时间:2020-08-18 01:38:43

标签: nestjs typeorm

@Column({ name: 'device_kind', type: 'int2', nullable: false })
deviceKind?: number;

任何人都可以解释此代码吗?我不明白他们为什么加上“?”标记。其中一些带有“!”而不是问号。 是什么意思?

1 个答案:

答案 0 :(得分:2)

这确实是一个Typescript问题,而不是TypeORM。

当您定义这样的属性时:

type Foo = {
  prop1?: number
}

您是说prop1是可选的。

当属性前面带有!时,表示您要告诉Typescript不要警告您未在构造函数中初始化它(通常在严格模式下会抱怨)。

示例:

class Foo {
  // Typescript does not complain about `a` because we set it in the constructor
  public a: number;

  // Typescript will complain about `b` because we forgot it.
  public b: number;

  // Typescript will not complain about `c` because we told it not to.
  public c!: number;

  // Typescript will not complain about `d` because it's optional and is
  // allowed to be undefined.
  public d?: number;

  constructor() {
    this.a = 5;
  }

}

应该注意的是,上一类中的c!情况实际上是一种告诉Typescript的方式:“我知道我在做什么,我知道我将它设置在某个地方,只是不在构造函数中。请不要抱怨。”

这与d?情况不同,因为这仅意味着d被允许为number {{1} }。