microsoft / microsoft/TypeScript
Optional chaining should always include `undefined` in its resolved type
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the TypeScript 3.7.5 example with optional chaining and its explicit string return type. Determine whether the intended fix is to include undefined in the resolved type or to reject optional chaining on non-nullable values; done means the chosen behavior is enforced consistently and covered by compiler tests.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100