@Column({ name: 'device_kind', type: 'int2', nullable: false })
deviceKind?: number;
任何人都可以解释此代码吗?我不明白他们为什么加上“?”标记。其中一些带有“!”而不是问号。 是什么意思?
答案 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} }。