类属性中的非null断言



我对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(即用户没有首选名称(?

或者,对于为什么在该属性上包含非null运算符,有更好的解释吗?例如排除未定义但包含null。

这主要是一个术语问题:

  • nullundefined是不同的,尽管语言的某些部分对它们的处理方式相似。(例如,非null断言运算符从其操作的表达式的域中消除nullundefined。(

  • 类属性声明后的!确定赋值断言运算符运算符,不是非null断言运算符。(它们都是用后缀!编写的,但非null断言出现在表达式之后,而明确赋值断言出现在变量/属性声明后面。(明确赋值断言告诉编译器在使用之前不需要验证变量或属性是否已初始化。明确赋值断言运算符与null无关。

如果不初始化属性或变量,如果从中读取,其值将为undefined,而不是null。如果启用了--strictPropertyInitialization编译器选项(或仅启用了包括它的--strict(,并且类属性的类型不包括undefined(而非null(,则必须在声明时立即对其进行初始化,在构造函数中无条件地初始化它,或者使用明确的赋值断言:

class Example {
a: string | undefined; // okay: includes undefined
b: string | null = "b"; // okay: initialized
c: string | null; // okay: assigned in constructor
d: string | null; // error: compiler cannot be sure it is assigned
e!: string | null; // okay: asserted as assigned
constructor() {
this.c = "c";
if (Math.random() < 1000) {
this.d = "d"
this.e = "e";
}
}
}

游乐场链接到代码

最新更新