-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Conditional typing for this["key1"]
is not possible because neither branch will be executed
#51288
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
Comments
It's probably a design limitation, because conditional types are deferred when the type is not known, and Is there any reason to write code like this? |
The reason for this is the following code (which should allow all public properties of class Test {
public key1: string = 'abc';
public key2: string|null = null;
public doSomething(): void {
setSomething(this, 'key1'); // doesn't work because it will call `setSomething<this>`, and then `this['key1']` doesn't fulfill the `extends string` condition
}
}
function setSomething<T>(a: T, b: KeysForTypeInContext<string, T>): void {
}
type KeysForTypeInContext<T, TContext> = {
[key in keyof TContext]: TContext[key] extends T ? key : never;
}[keyof TContext]; If there is a different way of doing this (without having to specify the However, I found the Typescript behavior in this case very strange - but thanks for the hint that |
The sort of logic you want to represent here isn't possible today. See #48992 |
I'd like to chime in here, as I think I'm seeing a very similar problem. Except that it is not with interface Ev<T> {
e: T;
}
interface Test {
finally: Ev<{status: "done"}>;
}
type Extends<T> = T extends Ev<infer E> ? number : string;
class C<T extends Test> {
constructor() {
const s1: Extends<T["finally"]> = "";
const s2: Extends<T["finally"]> = 1;
}
} The real life case is that interfaces Honestly, I find it a bit hard to grasp the concept of applying a ternary operator and getting neither of the branches evaluated. Wonder how that would work in "actual" language ;-)? |
Bug Report
π Search Terms
"this" key typing, conditional types on "this"
π Version & Regression Information
this
β― Playground Link
Playground link with relevant code
π» Code
π Actual behavior
this["key1"] extends string
is neither true nor false and no path of the conditional type is returned. It's not possible to assign either a string or a number to a variable with the type.π Expected behavior
this["key1"] extends string
should be true in the example above and therefore the first part of the conditional typing should get returned and theConditionalThisType
should benumber
. In all cases, it should be possible to assign at least either a string or a number because the documentation for conditional types states that either the first branch or the second branch will be returned:The text was updated successfully, but these errors were encountered: