useNullishCoalescing
Ta treść nie jest jeszcze dostępna w Twoim języku.
Summary
Section titled “Summary”- Diagnostic Category:
lint/nursery/useNullishCoalescing - This rule has a safe fix.
- The default severity of this rule is information.
- This rule belongs to the following domains:
- Sources:
- Inspired from
@typescript-eslint/prefer-nullish-coalescing
- Inspired from
How to configure
Section titled “How to configure”{ "linter": { "rules": { "nursery": { "useNullishCoalescing": "error" } } }}Description
Section titled “Description”Enforce using nullish coalescing operator (??) instead of logical or (||).
The ?? operator only checks for null and undefined, while || checks
for any falsy value including 0, '', and false. This can prevent bugs
where legitimate falsy values are incorrectly treated as missing.
This rule triggers when the left operand of || is possibly nullish (contains
null or undefined in its type). A safe fix is only offered when the type
analysis confirms the left operand can only be truthy or nullish (not other
falsy values like 0 or '').
By default, || expressions in conditional test positions (if/while/for/ternary)
are ignored, as the falsy-checking behavior is often intentional there. This can
be disabled with the ignoreConditionalTests option.
Examples
Section titled “Examples”Invalid
Section titled “Invalid”declare const maybeString: string | null;const value = maybeString || 'default'; // should use ??declare const maybeNumber: number | undefined;const value = maybeNumber || 0; // should use ??// Already using ??declare const maybeString: string | null;const value = maybeString ?? 'default';// Type is not nullish - no null or undefined in uniondeclare const definiteString: string;const value = definiteString || 'fallback';// In conditional test position (ignored by default)declare const cond: string | null;if (cond || 'fallback') { console.log('in if');}Related links
Section titled “Related links”Copyright (c) 2023-present Biome Developers and Contributors.