noNonNullAssertion
¥Summary
-
规则生效日期:
v1.0.0¥Rule available since:
v1.0.0 -
诊断类别:
lint/style/noNonNullAssertion¥Diagnostic Category:
lint/style/noNonNullAssertion -
此规则为推荐规则,默认启用。
¥This rule is recommended, which means is enabled by default.
-
此规则包含 unsafe 修复程序。
¥This rule has an unsafe fix.
-
此规则的默认严重级别为 warning。
¥The default severity of this rule is warning.
-
来源:
¥Sources:
¥How to configure
{ "linter": { "rules": { "style": { "noNonNullAssertion": "error" } } }}¥Description
禁止使用 ! 后缀运算符进行非空断言。
¥Disallow non-null assertions using the ! postfix operator.
TypeScript 的 ! 非空断言运算符向类型系统断言表达式不可为空,如 not null 或 undefined。使用断言告诉类型系统新信息通常表明代码不是完全类型安全的。通常最好构造程序逻辑,以便 TypeScript 了解值何时可以为空。
¥TypeScript’s ! non-null assertion operator asserts to the type system that an expression is non-nullable, as
in not null or undefined. Using assertions to tell the type system new information is often a sign that
code is not fully type-safe. It’s generally better to structure program logic so that TypeScript understands
when values may be nullable.
¥Examples
¥Invalid
interface Example { property?: string;}declare const foo: Example;const includesBaz = foo.property!.includes('baz');code-block.ts:5:21 lint/style/noNonNullAssertion FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠ Forbidden non-null assertion.
3 │ }
4 │ declare const foo: Example;
> 5 │ const includesBaz = foo.property!.includes(‘baz’);
│ ^^^^^^^^^^^^^
6 │
ℹ Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator
3 3 │ }
4 4 │ declare const foo: Example;
5 │ - const·includesBaz·=·foo.property!.includes(‘baz’);
5 │ + const·includesBaz·=·foo.property?.includes(‘baz’);
6 6 │
(b!! as number) = "test";code-block.ts:1:2 lint/style/noNonNullAssertion ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠ Forbidden non-null assertion.
> 1 │ (b!! as number) = “test”;
│ ^^^
2 │
¥Valid
interface Example { property?: string;}
declare const foo: Example;const includesBaz = foo.property?.includes('baz') ?? false;¥Related links
Biome v2.1 中文网 - 粤ICP备13048890号