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

Optional chaining should always include undefined in its resolved type #36672

Open
Svish opened this issue Feb 7, 2020 · 2 comments
Open

Optional chaining should always include undefined in its resolved type #36672

Svish opened this issue Feb 7, 2020 · 2 comments
Labels
In Discussion Not yet reached consensus Suggestion An idea for TypeScript

Comments

@Svish
Copy link

Svish commented Feb 7, 2020

TypeScript Version: 3.7.5

Search Terms: optional chaining return type

Code

I have a formatting function, where the input should always be a string, but in certain cases, from the backend, it's undefined for some reason. So to make sure the front-end at least doesn't crash when that happens, I added optional chaining, which fixed the issue.

But the types are kind of off now, and I didn't realize until now because Typescript didn't complain about anything.

export const formatAccountNumber = (account: string): string =>
  account?.replace(/^(\d{4})(\d{2})(\d{5})/, '$1 $2 $3');

Expected behavior: Should get an error/warning about something here. Preferably, I guess optional chaining should always expand the type to include undefined to whatever it is added to? Then, in this example, Typescript could say that the return type is string, but I'm trying to return string | undefined? Either that, or maybe it shouldn't be possible to use optional chaining on a value that does not include either the type undefined and/or null?

Actual behavior: No warnings or errors.

Related Issues: no

@nmain
Copy link

nmain commented Feb 7, 2020

This is the first discussion point of #36623. Also see #36163.

@RyanCavanaugh RyanCavanaugh added In Discussion Not yet reached consensus Suggestion An idea for TypeScript labels Feb 10, 2020
@RyanCavanaugh RyanCavanaugh changed the title Optional Chaining is not checked properly? Optional chaining should always include undefined in its resolved type Feb 10, 2020
@awjreynolds
Copy link

Just to say this one caught us out in our codebase and took a while to figure out as it wasn't being picked up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
In Discussion Not yet reached consensus Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

4 participants