JavaScript中的Assertion

var c = console.log;

c(true === undefined);

c(true == undefined);

c(true === null);

c(true == null);

c(true === 1);

c(true == 1);

c(true === 2);

c(true == 2);

c(true === [0]);

c(true == [0]);

c(true === [1]);

c(true == [1]);

c(true ==={0: 0});

c(true == {0:0});

c(true === '0');

c(true == '0');

c(true === 'true');

c(true == 'true');

c(true === 'false');

c(true == 'false');

转载于:https://www.cnblogs.com/Yaxian/p/4513163.html

在 TypeScript(TS),使用 `!` 进行非空断言 (`as !T`) 是为了强制检查某个值是否为非 null 或 undefined,但有时候这可能会触发 ESLint 的规则,如 `"@typescript-eslint/no-non-null-assertion"`,该规则禁止使用非空断言,认为其可能导致隐性的运行时错误。 解决这个问题有几种方法: 1. **关闭规则**:在你的项目 `.eslintrc.js` 文件,找到对应的 ESLint 规则配置,添加一条注释禁用它,例如: ```javascript "rules": { "@typescript-eslint/no-non-null-assertion": "off" } ``` 2. **理解并合理使用**:只有当你知道值确实不应该为 null 或 undefined 时,才使用断言。如果你不确定,可以考虑其他方法,如使用可选链操作符 (`?.`) 或条件判断。 3. **明确类型标注**:对于可能为 null 或 undefined 的变量,可以在类型标注时指定可能的值,减少非空断言的必要性: ```typescript let value: Maybe<string> = someVariable ?? ""; // 使用 Maybe<T> 来表示可能为 null 或 undefined 的 T ``` 4. **使用 TypeScript 的非空 assertion 类型运算符(`asserts`)**:从 TypeScript 4.6 开始,引入了新的非空 assertion 类型运算符 `asserts`。虽然它看起来像断言,但不会触发 ESLint 报警: ```typescript const notNull: asserts value is string = value; ``` 记住,非空断言通常是提高代码可靠性和可读性的工具,但过度使用可能隐藏真正的代码问题。所以在实际应用需要权衡。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值