Below function returns undefined
if parameter is null
otherwise returns the parameter’s value as-is.
function nullToUndefined<BasicType>(targetValue: BasicType | null): BasicType | undefined {
// `void 0` because `undefined` literal could be shadowed
// See https://eslint.org/docs/latest/rules/no-undefined
return targetValue === null ? void 0 : targetValue;
}
Although this function could be replaced with nullish coalescing in most cases, sometimes it could avoid trouble:
class User {
private _name?: string;
public set name(value: string | null) {
this._name = nullToUndefined(value);
this._name = value ?? undefined; // ESLint: Unexpected use of undefined.(no-undefined)
this._name = value ?? void 0; // ESLint: Expected 'undefined' and instead saw 'void'.(no-void)
}
}
Albeit inside nullToUndefined
ESLint will report no-void
, for the library it could be fine.
It works from the viewpoint of JavaScript, but in below case I got TS2322 error:
function appendUnits(target: number | null): string | undefined {
return typeof target === "number" ? `${ target }kb` : nullToUndefined(target);
}
Type 'string | null | undefined' is not assignable to type 'string | undefined'.
Type 'null' is not assignable to type 'string | undefined'.(2322)
Below code does not work:
function nullToUndefined<BasicType extends Exclude<unknown, null>>(targetValue: BasicType | null): BasicType | undefined {
return targetValue === null ? void 0 : targetValue;
}
The only working solution is overloading:
export default function nullToUndefined(targetValue: null): undefined;
export default function nullToUndefined<BasicType extends Exclude<unknown, null>>(targetValue: null): BasicType | undefined;
export default function nullToUndefined<BasicType>(targetValue: BasicType | null): BasicType | undefined {
return targetValue === null ? undefined : targetValue;
}
Are there ways to simplify the code?
1