我有一个 Angular 6 项目,我的问题是在模型类上定义可空属性的最佳方式是什么?
选项 1:使用 ?
运算符
export class ProductModel {
public name?: string;
}
选项 2:将属性定义为 string 和 null
export class ProductModel {
public name: string | null;
}
请注意,我在 tsconfig.json
中设置了 "strictNullChecks": true
。
也许这只是一种偏好,但如果有人可以帮助我提供一些背景提示和技巧或引用文章?
最佳答案
启用strictNullChecks
name?: string;
name 的类型是string |未定义
。
问题中的两个例子不仅语法略有不同,而且产生不同的结果:
type WithOptional = {
name?: string;
}
type WithNullable = {
name: string | null;
}
const withOptional: WithOptional = {}; // no error: name is optional
withOptional.name = null; // error: null is not assignable to string | undefined
const withNullable: WithNullable = {}; // error: name is missing
withNullable.name = undefined // error: undefined is not assingable to string | null
如果您希望名称既是可选的又可以为空,您可以将其定义为 name?: string |空;
关于angular - TypeScript Angular 项目 : use undefined or null for properties in classes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50423060/