I have a function called isDefined, which is implemented like so:
export function isDefined<T>(value: T): value is NonNullable<T> {
return value !== undefined && value !== null;
}
Functionality, it works. But, there's one small thing that I try to accomplis. Let's take this code for example:
const a: number | null | undefined = 1;
if (a !== undefined && a !== null) {
// a is inferred here as `number`
...
if (a !== undefined) {
//^^^^^^^^^^^^^^^ tslint/eslint will throw the following warning:
// "Expression is always true. (strict-type-predicates)"
}
}
Since I've already checked if a is defined, the lint will throw a warning that stating that again would be redundant.
If I try to replace it with isDefined, No warning will be thrown:
if (isDefined(a)) {
// a is inferred here as `number`
...
if (isDefined(a)) {
// linter throws nothing
}
}
I wasn't able to reproduce it in codesandbox since I cannot configure the eslint, but this is the code:
export function isDefined<T>(value: T): value is NonNullable<T> {
return value !== undefined && value !== null;
}
function linterWillThrowWarning<T>(value: T | null | undefined) {
if (value !== null && value !== undefined) {
if (value !== null) {
console.log(value);
}
}
}
function linterWontThrowWarning<T>(value: T | null | undefined) {
if (isDefined(value)) {
if (isDefined(value)) { // (I want it to throw)
console.log(value);
}
}
}