An ESLint plugin to prevent unsafe conversions to Number() from null or undefined values.
npm install --save-dev eslint-plugin-safe-numberThis plugin works ONLY in TypeScript projects.
It relies on the TypeScript Type Checker to determine if a variable is nullable. It will not work in standard JavaScript projects or without proper parserOptions.
module.exports = {
// ...
parser: "@typescript-eslint/parser",
parserOptions: {
ecmaVersion: "latest",
sourceType: "module",
// ⚠️ CRITICAL: Point to your TSConfig(s) to enable type-aware linting
project: ["./packages/*/tsconfig.json", "./tsconfig.json"],
tsconfigRootDir: __dirname,
},
plugins: ["safe-number"],
rules: {
// ... other rules
"safe-number/no-unsafe-number-conversion": "error",
},
};In JavaScript/TypeScript, passing null to the Number() constructor results in 0. This is often a source of subtle bugs in data processing, financial calculations, or optional form fields where "no value" should not be treated as "zero".
Number(null); // Result: 0 (Often unexpected)
Number(undefined); // Result: NaN
Array.from(["1", null], Number); // Unsafe!
getMaybeNullValue().then(Number); // Unsafe!The no-unsafe-number-conversion rule analyzes the TypeScript type of the value being passed to Number() and offers Suggestions (Quick Fixes) depending on the exact nullability of the value.
The goal is to prevent unsafe numeric conversions such as Number(null) or Number(undefined).
If the variable type is exactly Type | null:
const val: string | null = null;
Number(val);val !== null ? Number(val) : null;If the variable type is exactly Type | undefined:
const val: string | undefined = undefined;
Number(val);val !== undefined ? Number(val) : undefined;If the variable can be null or undefined in addition to the base type:
declare const val: string | null | undefined;
Number(val);val !== null && val !== undefined ? Number(val) : val;The rule also detects unsafe conversions in array callbacks such as map(Number):
const arr: (string | null)[] = ["1", null];
arr.map(Number);arr.map((val) => (val !== null ? Number(val) : null));The rule flags literal unsafe calls:
Number(null);
Number(undefined);These are treated as errors, but no auto-fix is offered, because the logic is ambiguous and should be resolved manually.