打字稿:的含义?和 !在类属性中 [英] Typescript: meaning of ? and ! in class properties

查看:58
本文介绍了打字稿:的含义?和 !在类属性中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

谁能解释一下这段代码?我不明白为什么他们添加了?"标记.其中一些有!"而不是问号.它们是什么意思?

Can anyone explain this code? I didn't understand why they added the '?' mark. and some of them has '!' instead of question mark. What do they mean?

推荐答案

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

This is a really a Typescript question, not TypeORM.

当您定义这样的属性时:

When you define a property like this:

type Foo = {
  prop1?: number
}

您是说 prop1 是可选的.

当一个属性以 ! 开头时,这意味着你告诉 Typescript 不要警告你没有在构造函数中初始化它(它通常会在严格模式下抱怨).

When a property is preceded with ! it means you are telling Typescript to not warn you that you didn't initialize it in the constructor (which it normally will complain about in strict mode).

示例:

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 的方式:我知道我在做什么,我知道我在某处设置它,只是不在构造函数中.请不要抱怨".

It should be noted that the c! case in the above class is really a way to tell Typescript: "I know what I'm doing, I know I'm setting this somewhere, just not in the constructor. Please don't complain".

这和 d? 的情况不一样,因为这只是意味着 d 可以是 number 未定义.

This is the not the same as the d? case, because this just means that d is allowed to be a number or undefined.

这篇关于打字稿:的含义?和 !在类属性中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆