Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Explicit check for undefined #36

Closed
2 tasks
Radeonmann opened this issue Apr 23, 2022 · 1 comment · Fixed by #59
Closed
2 tasks

Explicit check for undefined #36

Radeonmann opened this issue Apr 23, 2022 · 1 comment · Fixed by #59
Assignees
Milestone

Comments

@Radeonmann
Copy link
Collaborator

Radeonmann commented Apr 23, 2022

In some places the check for undefined values is done implicitly as follows:

const someValue = getSomeValue(); // string | undefined
if (!someValue) {
    throw new Error('Not initialized');
}

This can lead to errors, if the value is not undefined, but an empty string, an empty array, a number with value 0, a false Boolean, ...

The not operator ! returns true for such values and the guarding if triggers when it should not. The only place where the ! operator can be used for such a check is, when the behavior should be same for these falsy values and an undefined value. We should maybe consider to even use explicit checks in such cases to make the intention of the code more clear, even though this leads to more verbose code.

Check for only undefined before:

const someValue = getSomeValue(); // string | undefined
if (!someValue) {
    throw new Error('Not initialized'); // will throw on empty string
}

Check for only undefined better:

const someValue = getSomeValue(); // string | undefined
if (someValue === undefined) {
    throw new Error('Not initialized'); // will only throw on undefined
}

Check for undefined and falsy before:

let hasValues: boolean;
const someValues = getSomeValues(); // number[] | undefined
if (!someValues) {
    hasValues = false;
} else {
    hasValues = true;
}

Check for undefined and falsy more explicit:

let hasValues: boolean;
const someValues = getSomeValues(); // number[] | undefined
if ((someValues === undefined) || (someValues.length === 0)) {
    hasValues = false;
} else {
    hasValues = true;
}

TODO:

  • Decide if checks for undefined and falsy should be replaced by more explicit code
  • Find all occurrences of implicit checks and replace with explicit checks
@Radeonmann Radeonmann added this to the future-version milestone Apr 23, 2022
@Radeonmann Radeonmann self-assigned this Apr 23, 2022
@Radeonmann
Copy link
Collaborator Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant