Skip to content

Incorporate bang operator hack - #22971

Closed
Wesley Wigham (weswigham) wants to merge 1 commit into
microsoft:masterfrom
weswigham:hotfix-bang-operator
Closed

Wesley Wigham (weswigham) wants to merge 1 commit into
microsoft:masterfrom
weswigham:hotfix-bang-operator

Conversation

@weswigham

Copy link
Copy Markdown
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
Copy Markdown

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
Copy Markdown
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
Copy Markdown
Contributor

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.

@microsoft Microsoft (microsoft) locked as resolved and limited conversation to collaborators Oct 21, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants