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

Investigate (possibly contextual) truthiness narrowing of type parameters #49005

Closed
DanielRosenwasser opened this issue May 6, 2022 · 0 comments · Fixed by #49119
Closed
Assignees
Labels
Experimentation Needed Someone needs to try this out to see what happens Fix Available A PR has been opened for this issue In Discussion Not yet reached consensus Suggestion An idea for TypeScript

Comments

@DanielRosenwasser
Copy link
Member

In the TypeScript 4.7 timeframe, we introduced stricter behavior in strictNullChecks around unconstrained type parameters and empty/weak object types in #48366.

function foo<T>(x: T) {
    // should be an error because T could be null/undefined
    let obj: {} = x;
}

However, we but had to revert it back before our release candidate in #48923 because it was so invasive, and it really didn't catch a lot of bugs.

Still, we found a few examples of false-positive cases where users properly narrowed generics, but were encountering the error (#48468).

function foo<T>(x: T) {
    if (!x) return;

    // Should work.
    let obj: {} = x;
}

We wondered if we could provide some degree of narrowing. One experiment was in #48576, where we would only do narrowing in certain contexts on unconstrained type parameters to avoid invasive changes and narrowing time, but it is fairly specific to unconstrained type parameters, and provides poor error messages.

Another idea that @ahejlsberg and @RyanCavanaugh had was to leverage intersection types with {} to narrow truthiness checks. At the moment, the ideas involve being more aggressive in subtype/supertype reduction with {}, so this may introduce surprising changes; however, if we find the results are good, maybe we can take another swing at #48366 down the road.

@DanielRosenwasser DanielRosenwasser added Suggestion An idea for TypeScript In Discussion Not yet reached consensus Experimentation Needed Someone needs to try this out to see what happens labels May 6, 2022
@DanielRosenwasser DanielRosenwasser added this to the TypeScript 4.8.0 milestone May 6, 2022
@typescript-bot typescript-bot added the Fix Available A PR has been opened for this issue label May 21, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Experimentation Needed Someone needs to try this out to see what happens Fix Available A PR has been opened for this issue In Discussion Not yet reached consensus Suggestion An idea for TypeScript
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants