Skip to content

Validation of variable is not undefined doesn't work if it's not done directly inside if statement #52429

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

Closed
eliezra236 opened this issue Jan 26, 2023 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@eliezra236
Copy link

eliezra236 commented Jan 26, 2023

Bug Report

πŸ”Ž Search Terms

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

const map = new Map<string, number>();
map.set('a', 1);
const a = map.get('a');

const isAValid = Boolean(a);

if (!isAValid) {
    throw Error('no a');
}

const aCopy: number = a;

if (!a) {
    throw Error('no a')
}

const aCopy2: number = a;

πŸ™ Actual behavior

In the first example aCopy gives error because it can be undefined according to typescript

πŸ™‚ Expected behavior

aCopy should be defined to be a number.

@DanielRosenwasser
Copy link
Member

We don't really understand that Boolean is testing for truthiness. If you change your code to use !!, you do get the desired result.

declare const a: number | undefined;

const isAValid = !!a; // <- here

if (!isAValid) {
    throw Error('no a');
}

const aCopy: number = a;

If you really do want to use Boolean like this, I guess you could add a signature with a type predicate like this to the global state:

interface BooleanConstructor {
    <T>(x: T): x is Exclude<T, null | undefined | 0 | "" | false>;
}

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jan 26, 2023
@RyanCavanaugh
Copy link
Member

#16655

@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants