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

NonNullable behaves differently when passing a property type from this #36061

Closed
shilangyu opened this issue Jan 7, 2020 · 5 comments
Closed
Assignees
Labels
Needs Investigation This issue needs a team member to investigate its status.

Comments

@shilangyu
Copy link

TypeScript Version: 3.7.2

Search Terms:
NonNullable this this[] this property nonnullable
Code

type SomeType = string | undefined

class Test {
    prop: SomeType

    func1 = (): this['prop'] => {
        return this.prop
    }

    func2 = (): SomeType => {
        return this.prop
    }

    func3 = (): NonNullable<this['prop']> => {
        return this.prop!
    }

    func4 = (): NonNullable<SomeType> => {
        return this.prop!
    }
}

Expected behavior:

This code compiles correctly, this['prop'] and SomeType point to the same type.

Actual behavior:

func3 is not happy with the return statement: Type 'string' is not assignable to type 'NonNullable<this["prop"]>'.

Playground Link: link

Related Issues: none

@AnyhowStep
Copy link
Contributor

AnyhowStep commented Jan 7, 2020

Workaround,

type SomeType = string | undefined

class Test {
    prop: SomeType

    func3 = (): NonNullable<this['prop']> => {
        const tmp: this["prop"] = this.prop;
        return tmp!
    }

}

Playground

@RyanCavanaugh RyanCavanaugh added the Needs Investigation This issue needs a team member to investigate its status. label Jan 13, 2020
@RyanCavanaugh
Copy link
Member

@weswigham can you link to the proper duplicate please

@shilangyu
Copy link
Author

Tried v3.8, still seems to not work. I also tried to find the duplicate issue but I couldn't (probably a broader topic)

@weswigham
Copy link
Member

There's another similar issue to this one to do with this and NonNullable<this> not being compatible, but in this case the issue is that when we do a property access on this, we actually get the constraint of the access (so we report the "current" type rather than this["prop"]), which, when NonNullable'd, then produces a (less precise) result.

#26942 is a dupe with a slightly inaccurate answer (even adding a cast is not sufficient, because of what I described above).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Needs Investigation This issue needs a team member to investigate its status.
Projects
None yet
Development

No branches or pull requests

5 participants