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
Foohas a methodgetStringAttr, which accepts the name of the class property and returns it back if it is a string, orneverif it is not a string
Expected behavior:
Regardless of where the getStringAttr method is called, it should have consistent behavior.
Actual behavior:
- Calling
getStringAttrby creating a new class instance works fine - Calling
getStringAttrfrom a different class method (within the class body) makes it infer incorrect types - The
getStringAttr('dob')should returnneverin both cases. But within the class body it returnsstring. - The
getStringAttr('age')should returnneverin both cases and it does so.
Related Issues: Cannot find any
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Reactions: 10
- Comments: 23 (5 by maintainers)
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