angular - TypeScript Angular 项目 : use undefined or null for properties in classes?

标签 angular typescript null undefined

我有一个 Angular 6 项目,我的问题是在模型类上定义可空属性的最佳方式是什么?

选项 1:使用 ? 运算符

export class ProductModel {
    public name?: string;
}

选项 2:将属性定义为 stringnull

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/

相关文章:

angular - Codecov、Github 操作和 Angular 11 "No coverage report found"

javascript - 无法对未安装的组件执行 React 状态更新

arrays - Angular 5,来自 API 的 JSON 数组

sql - 在sql server中将int增加1?

angular - Angular2 Http 请求如何以二进制形式返回正文?

angular - 使用带有 `built` 文件夹的 WebStorm 在 Angular 2 中运行测试

css - images/css/js 等静态文件的相对路径

javascript - ESLint:防止对非标准文件扩展名进行 lint

ruby-on-rails - Ruby on Rails : params is nil. 未定义方法 `[]' 为 nil:NilClass

sql-server - 存储过程以处理空参数