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

Incorporate bang operator hack #22971

Closed
wants to merge 1 commit into from

Conversation

weswigham
Copy link
Member

Fixes half of #22934

With this change, the ! operator only applies the NonNullable<T> type if T is an instantiable type (or union thereof) constrained to null or undefined (or unconstrained).

This does not, however, fix the underlying conceptual problem, which is that when you write

class X {
    fn(): void {
        // Type 'this' is not assignable to type 'NonNullable<this>'.
        //  Type 'X' is not assignable to type 'NonNullable<this>'.
        const x: NonNullable<this> = this;
        //    ~
    }
}

One would expect the assignment to work, as the this type can never include null or undefined (barring shenanigans like X & undefined).

@Jessidhia
Copy link

undefined is a value that this can legitimately have at runtime in strict mode code, though. But the --noImplicitThis mode probably catches most of the code that doesn't account for this.

@weswigham
Copy link
Member Author

@Kovensky AFAIK a class method we consider to have a strongly typed this in strict mode and don't allow calling it without one (and one compatable with the this type from the original declaration at that). The type of this is a method is an implicit type variable extending the containing class - such a definition does not allow for null or undefined values. It's the fact that it's a type parameter that makes it not work like you'd expect. If you tried to assign an X to a NonNullable<X>, it'd work fine because NonNullable<X> immediately simlifies to just X.

@typescript-bot
Copy link
Collaborator

Thanks for your contribution. This PR has not been updated in a while and cannot be automatically merged at the time being. For housekeeping purposes we are closing stale PRs. If you'd still like to continue working on this PR, please leave a message and one of the maintainers can reopen it.

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.

3 participants