Naz*_*san 2 typescript typeorm nestjs
@Column({ name: 'device_kind', type: 'int2', nullable: false })
deviceKind?: number;
Run Code Online (Sandbox Code Playgroud)
谁能解释一下这段代码吗?我不明白他们为什么添加“?” 标记。其中一些有“!” 而不是问号。他们的意思是什么?
这实际上是一个 Typescript 问题,而不是 TypeORM。
当您定义这样的属性时:
type Foo = {
prop1?: number
}
Run Code Online (Sandbox Code Playgroud)
你说的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;
}
}
Run Code Online (Sandbox Code Playgroud)
应该注意的是,c!上面类中的情况实际上是告诉 Typescript 的一种方式:“我知道我在做什么,我知道我正在某个地方设置它,只是不在构造函数中。请不要抱怨”。
这与情况不同d?,因为这只是意味着d允许是 anumber 或 undefined。
| 归档时间: |
|
| 查看次数: |
2054 次 |
| 最近记录: |