Skip to content

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

Closed

Description

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

Activity

  1. AnyhowStep commented on Jan 7, 2020

    @AnyhowStep
    Contributor

    Workaround,

    type SomeType = string | undefined
    
    class Test {
        prop: SomeType
    
        func3 = (): NonNullable<this['prop']> => {
            const tmp: this["prop"] = this.prop;
            return tmp!
        }
    
    }

    Playground

  2. added
    Needs Investigation
    on Jan 13, 2020
  3. RyanCavanaugh commented on Jan 13, 2020

    @RyanCavanaugh
    Member

    Wesley Wigham (@weswigham) can you link to the proper duplicate please

  4. shilangyu commented on Feb 23, 2020

    @shilangyu
    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)

  5. weswigham commented on Mar 4, 2020

    @weswigham
    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

Metadata

Metadata

Labels

Needs Investigation

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions