【发布时间】:2021-04-28 23:42:32
【问题描述】:
我对 typescript 还很陌生,并且已经在网上搜索过,试图找到对此的解释。
最近我一直在做一个项目,并想使用 sequelize 来处理它。在阅读文档的打字稿部分时,我遇到了以下示例:
// These are all the attributes in the User model
interface UserAttributes {
id: number;
name: string;
preferredName: string | null;
}
// Some attributes are optional in `User.build` and `User.create` calls
interface UserCreationAttributes extends Optional<UserAttributes, "id"> {}
class User extends Model<UserAttributes, UserCreationAttributes>
implements UserAttributes {
public id!: number; // Note that the `null assertion` `!` is required in strict mode.
public name!: string;
public preferredName!: string | null; // for nullable fields
// timestamps!
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
//other code
}
在类内部,preferredName 也有非 null 断言运算符,但随后会在其类型中包含 null。
这是否会覆盖静态类型检查,因为它在运行时可能为 null(即用户没有首选名称)?
或者是否有更好的解释来解释为什么它们会在该属性上包含非空运算符?比如排除undefined但包含null。
【问题讨论】:
-
对我来说,它看起来只是为了保持一致性,或者是使用自动化工具创建的,或者它表明虽然它没有在构造函数中初始化,但它实际上在创建时被赋予了正确的模型值。我怀疑这是否意味着
preferredName不为空
标签: typescript sequelize-typescript