如何在不屏蔽错误的情况下删除属性“消息”在 ts 中没有初始化错误

问题描述 投票:0回答:2

我正在使用 ts 和 Sequelize 在 Node js 中创建模型

import { Table, Column, Model, AllowNull } from 'sequelize-typescript';

@Table
class Person extends Model {
  @Column
  @AllowNull(false)
  name: string;

  @Column
  birthday: Date;
}

但是我得到属性“名称”没有初始化程序,并且在构造函数中没有明确分配

我不想用空字符串初始化它。但我也不想补充

strictPropertyInitialization": false

并掩盖错误。

正确的解决方法是什么?

node.js typescript postgresql sequelize.js sequelize-typescript
2个回答
1
投票

您可以使用

!
?
,如下所示:

@Table
class Person extends Model {
  @Column
  @AllowNull(false)
  name!: string; // <---- Type: string

  @Column
  birthday?: Date; // <---- Type: Date | undefined
}

!
符号用于指示属性永远不会未定义,这意味着如果未为其分配值,则会抛出错误。另一方面,
?
符号用于指示属性可以是未定义的,这意味着如果没有为其分配值,它将被视为未定义。


0
投票

在 NestJs 中,使用 @nestjs/common v10.0.0(这一天的新版本)

他们在其 tsconfig.json

上使用此配置
{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "ES2021",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": false,   // <---- YOU WANT THIS
    "noImplicitAny": false,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false
  }
}

规则“strictNullChecks”说:类型检查时,考虑 null 和 undefined。

因此,将此规则设置为 false,也可以解决此问题。

© www.soinside.com 2019 - 2024. All rights reserved.