prefer-nullish-coalescing
Enforce using the nullish coalescing operator instead of logical assignments or chaining.
在 ESLint 配置 中扩展"plugin:@typescript-eslint/stylistic-type-checked"
可启用此规则。
此规则报告的一些问题可以通过编辑器 建议 手动修复。
该规则需要 类型信息 才能运行。
??
无效合并运行时运算符允许在处理 null
或 undefined
时提供默认值。
因为空合并运算符仅在原始值是 null
或 undefined
时才进行合并,所以它比依赖于逻辑 OR 运算符链接 ||
(在任何虚假值上进行合并)要安全得多。
英:The ??
nullish coalescing runtime operator allows providing a default value when dealing with null
or undefined
.
Because the nullish coalescing operator only coalesces when the original value is null
or undefined
, it is much safer than relying upon logical OR operator chaining ||
, which coalesces on any falsy value.
此规则报告你何时可以考虑更换:
英:This rule reports when you may consider replacing:
||
运算符与??
||=
运算符与??=
如果未启用 strictNullChecks
,则此规则将无法按预期工作。
module.exports = {
"rules": {
"@typescript-eslint/prefer-nullish-coalescing": "error"
}
};
选项
ignoreTernaryTests
将此选项设置为 true
将导致规则忽略任何可以通过使用 nullish 合并运算符来简化的三元表达式。 默认设置为 false
。
英:Setting this option to true
will cause the rule to ignore any ternary expressions that could be simplified by using the nullish coalescing operator. This is set to false
by default.
ignoreTernaryTests: false
的代码不正确,ignoreTernaryTests: true
的正确代码:
英:Incorrect code for ignoreTernaryTests: false
, and correct code for ignoreTernaryTests: true
:
const foo: any = 'bar';
foo !== undefined && foo !== null ? foo : 'a string';
foo === undefined || foo === null ? 'a string' : foo;
foo == undefined ? 'a string' : foo;
foo == null ? 'a string' : foo;
const foo: string | undefined = 'bar';
foo !== undefined ? foo : 'a string';
foo === undefined ? 'a string' : foo;
const foo: string | null = 'bar';
foo !== null ? foo : 'a string';
foo === null ? 'a string' : foo;
Open in PlaygroundignoreTernaryTests: false
的正确代码:
英:Correct code for ignoreTernaryTests: false
:
const foo: any = 'bar';
foo ?? 'a string';
foo ?? 'a string';
foo ?? 'a string';
foo ?? 'a string';
const foo: string | undefined = 'bar';
foo ?? 'a string';
foo ?? 'a string';
const foo: string | null = 'bar';
foo ?? 'a string';
foo ?? 'a string';
Open in PlaygroundignoreConditionalTests
将此选项设置为 true
将导致规则忽略条件测试中的任何案例。 默认设置为 false
。
英:Setting this option to true
will cause the rule to ignore any cases that are located within a conditional test. This is set to false
by default.
通常,条件测试中的表达式会故意使用逻辑或运算符的虚假失败行为,这意味着将运算符固定为空合并运算符可能会导致错误。
英:Generally expressions within conditional tests intentionally use the falsy fallthrough behavior of the logical or operator, meaning that fixing the operator to the nullish coalesce operator could cause bugs.
如果你希望执行更严格的条件测试,则应考虑使用 strict-boolean-expressions
规则。
英:If you're looking to enforce stricter conditional tests, you should consider using the strict-boolean-expressions
rule.
ignoreConditionalTests: false
的代码不正确,ignoreConditionalTests: true
的正确代码:
英:Incorrect code for ignoreConditionalTests: false
, and correct code for ignoreConditionalTests: true
:
declare const a: string | null;
declare const b: string | null;
if (a || b) {
}
if ((a ||= b)) {
}
while (a || b) {}
while ((a ||= b)) {}
do {} while (a || b);
for (let i = 0; a || b; i += 1) {}
a || b ? true : false;
Open in PlaygroundignoreConditionalTests: false
的正确代码:
英:Correct code for ignoreConditionalTests: false
:
declare const a: string | null;
declare const b: string | null;
if (a ?? b) {
}
if ((a ??= b)) {
}
while (a ?? b) {}
while ((a ??= b)) {}
do {} while (a ?? b);
for (let i = 0; a ?? b; i += 1) {}
a ?? b ? true : false;
Open in PlaygroundignoreMixedLogicalExpressions
将此选项设置为 true
将导致规则忽略属于混合逻辑表达式(带有 &&
)的任何逻辑或表达式。 默认设置为 false
。
英:Setting this option to true
will cause the rule to ignore any logical or expressions that are part of a mixed logical expression (with &&
). This is set to false
by default.
通常,混合逻辑表达式中的表达式会故意使用逻辑或运算符的虚假失败行为,这意味着将运算符固定为空合并运算符可能会导致错误。
英:Generally expressions within mixed logical expressions intentionally use the falsy fallthrough behavior of the logical or operator, meaning that fixing the operator to the nullish coalesce operator could cause bugs.
如果你希望执行更严格的条件测试,则应考虑使用 strict-boolean-expressions
规则。
英:If you're looking to enforce stricter conditional tests, you should consider using the strict-boolean-expressions
rule.
ignoreMixedLogicalExpressions: false
的代码不正确,ignoreMixedLogicalExpressions: true
的正确代码:
英:Incorrect code for ignoreMixedLogicalExpressions: false
, and correct code for ignoreMixedLogicalExpressions: true
:
declare const a: string | null;
declare const b: string | null;
declare const c: string | null;
declare const d: string | null;
a || (b && c);
a ||= b && c;
(a && b) || c || d;
a || (b && c) || d;
a || (b && c && d);
Open in PlaygroundignoreMixedLogicalExpressions: false
的正确代码:
英:Correct code for ignoreMixedLogicalExpressions: false
:
declare const a: string | null;
declare const b: string | null;
declare const c: string | null;
declare const d: string | null;
a ?? (b && c);
a ??= b && c;
(a && b) ?? c ?? d;
a ?? (b && c) ?? d;
a ?? (b && c && d);
Open in Playground注意: 此特定情况的错误将作为建议显示(见下文),而不是修复。 这是因为在混合逻辑表达式中自动将 ||
转换为 ??
并不总是安全的,因为我们无法得知运算符的预期优先级。 请注意,根据设计,??
在同一表达式中与 &&
或 ||
一起使用时需要括号。
英:NOTE: Errors for this specific case will be presented as suggestions (see below), instead of fixes. This is because it is not always safe to automatically convert ||
to ??
within a mixed logical expression, as we cannot tell the intended precedence of the operator. Note that by design, ??
requires parentheses when used with &&
or ||
in the same expression.
ignorePrimitives
如果你想忽略包含某些可能为假的基元类型的操作数的表达式,那么你可以传递一个包含每个基元的布尔值的对象:
英:If you would like to ignore expressions containing operands of certain primitive types that can be falsy then you may pass an object containing a boolean value for each primitive:
string: true
,忽略null
或undefined
与string
的并集(默认值: false)。number: true
,忽略null
或undefined
与number
的并集(默认值: false)。bigint: true
,忽略null
或undefined
与bigint
的并集(默认值: false)。boolean: true
,忽略null
或undefined
与boolean
的并集(默认值: false)。
ignorePrimitives: { string: false }
的代码不正确,ignorePrimitives: { string: true }
的正确代码:
英:Incorrect code for ignorePrimitives: { string: false }
, and correct code for ignorePrimitives: { string: true }
:
const foo: string | undefined = 'bar';
foo || 'a string';
Open in PlaygroundignorePrimitives: { string: false }
和 ignorePrimitives: { string: true }
的正确代码:
英:Correct code for both ignorePrimitives: { string: false }
and ignorePrimitives: { string: true }
:
const foo: string | undefined = 'bar';
foo ?? 'a string';
Open in Playground另外,如果你想忽略所有基元类型,可以设置 ignorePrimitives: true
。 相当于 ignorePrimitives: { string: true, number: true, bigint: true, boolean: true }
。
英:Also, if you would like to ignore all primitives types, you can set ignorePrimitives: true
. It is equivalent to ignorePrimitives: { string: true, number: true, bigint: true, boolean: true }
.
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing
如果将其设置为 false
,则该规则将在 tsconfig.json
未将 strictNullChecks
编译器选项(或 strict
)设置为 true
的每个文件上出错。
英:If this is set to false
, then the rule will error on every file whose tsconfig.json
does not have the strictNullChecks
compiler option (or strict
) set to true
.
如果没有 strictNullChecks
,TypeScript 本质上会从类型中删除 undefined
和 null
。 这意味着当该规则检查变量 它无法判断该变量可能是 null
或 undefined
的类型时,这实际上使该规则毫无用处。
英:Without strictNullChecks
, TypeScript essentially erases undefined
and null
from the types. This means when this rule inspects the types from a variable, it will not be able to tell that the variable might be null
or undefined
, which essentially makes this rule useless.
你应该使用 strictNullChecks
来确保代码库中的完全类型安全。
英:You should be using strictNullChecks
to ensure complete type-safety in your codebase.
如果由于某种原因你无法打开 strictNullChecks
,但仍想使用此规则 - 你可以使用此选项来允许它 - 但要知道,在编译器选项关闭的情况下,此规则的行为是未定义的。 如果你使用此选项,我们将不接受错误报告。
英:If for some reason you cannot turn on strictNullChecks
, but still want to use this rule - you can use this option to allow it - but know that the behavior of this rule is undefined with the compiler option turned off. We will not accept bug reports if you are using this option.
何时不使用它
如果你不使用 TypeScript 3.7(或更高版本),那么你将无法使用此规则,因为不支持该运算符。
英:If you are not using TypeScript 3.7 (or greater), then you will not be able to use this rule, as the operator is not supported.
进一步阅读
选项
该规则接受以下选项
type Options = [
{
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing?: boolean;
ignoreConditionalTests?: boolean;
ignoreMixedLogicalExpressions?: boolean;
ignorePrimitives?:
| {
bigint?: boolean;
boolean?: boolean;
number?: boolean;
string?: boolean;
[k: string]: unknown;
}
| true;
ignoreTernaryTests?: boolean;
},
];
const defaultOptions: Options = [
{
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: false,
ignoreConditionalTests: false,
ignoreTernaryTests: false,
ignoreMixedLogicalExpressions: false,
ignorePrimitives: {
bigint: false,
boolean: false,
number: false,
string: false,
},
},
];