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

let x? allows initial undefined value + type inference; let x? = y for simple y #1654

Merged
merged 4 commits into from
Dec 21, 2024

Conversation

edemaine
Copy link
Collaborator

Previously, let x? compiled to the invalid TypeScript let x?. Now it compiles to let x = undefined. As this playground shows, this seems to allow for the initial undefined value (no error about access before initialized) as well as type inference.

This PR also makes let x? = 5 compile to let x = 5 (instead of leaving the invalid ? in there). I wanted to compile it to let x: undefined | typeof 5 = 5, but sadly this isn't valid TypeScript:

TypeScript intentionally limits the sorts of expressions you can use typeof on. Specifically, it’s only legal to use typeof on identifiers (i.e. variable names) or their properties.

Copy link
Contributor

@STRd6 STRd6 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A good improvement. We could check for common literal types: string, number, bigint, and generate the corresponding type | undefined in those cases.

@edemaine
Copy link
Collaborator Author

Ah, good idea. I had actually written code to do the rewriting into typeof before realizing that it didn't always work, so I could use that, modified to work in just the good cases (member expression and identifier). And I added a new literalType helper for literal types, and error in the other cases.

@edemaine edemaine changed the title let x? allows initial undefined value + type inference let x? allows initial undefined value + type inference; let x? = y for simple y Dec 21, 2024
@edemaine edemaine merged commit fbc9b46 into main Dec 21, 2024
3 checks passed
@edemaine edemaine deleted the let-question branch December 21, 2024 21:11
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

Successfully merging this pull request may close these issues.

2 participants