Typescript :?の意味 と!クラスのプロパティで

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

誰かがこのコードを説明できますか?なぜ彼らが「?」を追加したのか理解できませんでした。マーク。そしてそれらのいくつかは「!」を持っています 疑問符の代わりに。それらはどういう意味ですか?

回答

2 Evert Aug 18 2020 at 01:49

これは実際には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に次のように伝える方法であることに注意してください。「コンストラクターではなく、どこかに設定していることを知っています。文句を言わないでください」。

これは、aまたはであるd?ことdが許可されていることを意味するため、ケースと同じではありません。number undefined