TypeScript: Lookup type on `this` unexpectedly takes `true` branch of conditional type

  • Asked on Gitter
  • Tried my best to search existing issues
  • Tried questioning my understanding, but still the behavior feels weird to me
  • Finally, I am forced to create this issue (though I know, the issues list is too big)

TypeScript Version: v3.8.3 and Nightly Search Terms: Generics within class body, Generics in class body

Code

type IsString<T extends any, K extends keyof T> = T[K] extends string ? T[K] : never

class Foo {
  public username!: string
  public age!: number
  public dob!: { [key: string]: any }

  public getStringAttr<T, K extends keyof T>(this: T, key: K): IsString<T, K> {
    return {} as unknown as IsString<T, K>
  }

  public someInternalFunction() {
    this.getStringAttr('dob')
  }
}

new Foo().getStringAttr('dob')

The above is just a dummy code to reproduce the issue with minimum effort.

  • The class Foo has a method getStringAttr, which accepts the name of the class property and returns it back if it is a string, or never if it is not a string

Expected behavior:

Regardless of where the getStringAttr method is called, it should have consistent behavior.

Actual behavior:

  • Calling getStringAttr by creating a new class instance works fine
  • Calling getStringAttr from a different class method (within the class body) makes it infer incorrect types
  • The getStringAttr('dob') should return never in both cases. But within the class body it returns string.
  • The getStringAttr('age') should return never in both cases and it does so.

Playground Link: https://www.typescriptlang.org/play/index.html?ssl=1&ssc=1&pln=17&pc=31#code/C4TwDgpgBAkgzgZWAJwJYDsDmAeAKlCAD2AnQBM4oBDdEAGigGkDjSKoBrCEAewDMouAHxQAvIIDajALosS5SnBQZMUAPySZUAFxR0EAG4RkAWABQ5gMYAbKnEoAxHjygBvc1ChgArgCNrqJZQ3nDG6FQAthAAhLpKaFgeXn4BQVSYMbro3hG+xkk+-oFQZDy+sW5QElwgccpY0ro0IFAAvuYFKcUZwEgJmACCwCh4DMxE8uw1-IJCABTAABaocLq4DDW6jACUuvB9KqNMIu5mnp7IEMDeyOhurdSU3ugc6DwA7nd2sIj1OOvHJLtCxnZJFIJwHhRGDoEi3KjWBzPSzAVA8dBzbZuJKeJYrAB0PQOWCGKDmAHJSr5ydsgeZgeZ9O8oE4eJjCVdiYNhsgKVSaUA

Related Issues: Cannot find any

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 10
  • Comments: 23 (5 by maintainers)

Most upvoted comments

Maybe you are not aware of this, but this bug creates an issue in AdonisJS ORM. Many people are encountering this bug, not only one. We tell them to wait since we created this issue.

Some discussions about it:

How about moving the milestone to 4.7?

Faced this issue today.

Such a big company like Microsoft is rescheduling a bug for 2 years with no explanation altogether. No wonder why teams (Deno) are slowing moving away from TS

Hello 👋

Do I have to do anything special to get this fixed. It is a bug and I don’t think that a bug should be in demand to get attention