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

Boolean wrapped values don't refine that value to not be undefined #52910

Closed
4 of 5 tasks
lukeapage opened this issue Feb 22, 2023 · 2 comments
Closed
4 of 5 tasks

Boolean wrapped values don't refine that value to not be undefined #52910

lukeapage opened this issue Feb 22, 2023 · 2 comments

Comments

@lukeapage
Copy link

lukeapage commented Feb 22, 2023

Suggestion

πŸ” Search Terms

Boolean refine wrapped

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

if you wrap a value in Boolean() and use it in a conditional, it should still refine it to be not null or undefined.

πŸ“ƒ Motivating Example

In JSX its common to do the following

x && <Component x={x} />

but we have issues where if x is falsy but not accepted as a non value in jsx it can leak the type, so there is a lint rule to protected against it

https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-leaked-render.md

the least invasive fix of the lint rule is to wrap x in Boolean

Boolean(x) && <Component x={x} />

but that breaks typescripts ability to refine x.

example:

function a(x: undefined|null|{a: boolean}) {
    Boolean(x) && b(x);
}

function b(x: {a: boolean}) {

}

It is possible to fix this with something like this

interface BooleanConstructor {
    <T extends {} | string | number | boolean | Array<any>>(
        value?: T | undefined | null | '' | false,
    ): value is T;
}

playground link

Is there a reason to not have the above in the library - does it make typescript slower?

@MartinJohns
Copy link
Contributor

Another duplicate of #16655.

@lukeapage
Copy link
Author

Thanks, I did search and didn't find that one.

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

No branches or pull requests

2 participants