强制使用空值合并运算符(??)而不是逻辑运算符。
规则配置
// code-linter.json5
{
"rules": {
"@typescript-eslint/prefer-nullish-coalescing": "error"
}
} 正例
function getText1(): string | undefined {
return 'bar';
}
function getText2(): string | null {
return 'bar';
}
const foo1: string | undefined = getText1();
export const v1 = foo1 ?? 'a string';
const foo2: string | null = getText2();
export const v2 = foo2 ?? 'a string'; 反例
declare const a: string | null;
declare const b: string | null;
export const c = a || b;