-
Notifications
You must be signed in to change notification settings - Fork 12.8k
this index with unions outputs intersections? #49393
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
This is by design and has nothing to do with interface I { a: string, b: number };
const v: I = { a: "foo", b: 812 };
const k = Math.random() >= 0.5 ? 'a': 'b';
// note: the type being assigned to below is I['a' | 'b']
v[k] = "bar"; // error - only 50/50 chance this is type-correct The only way the above could be typesafe is you could somehow come up with a value of type See #30769. |
It has something to do with |
Ah, I didn't realize the case with a concrete type is different. I should know by now that "TypeScript" and "consistency" are two words that don't belong in the same sentence. π |
I see. It makes sense to me now. But the inconsistency is confusing. The original issue I met is actually a little bit different. It may or may not be the same issue as this one I posted. class Base {
numFnWithThis<T extends NumKeys<this>>(key: T) {}
}
class Sub extends Base {
a!: number;
b!: string;
numFnWithConcrete<T extends NumKeys<Sub>>(key: T) {}
test() {
this.numFnWithThis('a'); // error: Argument of type 'string' is not assignable to parameter of type 'NumKeys<this>'.(2345)
this.numFnWithConcrete('a'); // ok
}
}
type NumKeys<T extends object> = {
[K in keyof T]: T[K] extends number ? K : never;
}[keyof T]; I have a method in base class that accepts certain types of property keys of the concrete class. The type filter helper ( |
It's consistent, just consistent with a different set of rules than you were expecting π The general way to think of it is that expressions involving The second example is tricky because TS is warning you about a condition that, by construction, can't actually occur in this sample. It's not safe in general to eagerly resolve |
This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
Bug Report
π Search Terms
π Version & Regression Information
This changed between versions 3.3.3 and 3.5.1, and it keeps the behavior since then to the current latest version (at least 4.7.3).
β― Playground Link
Playground link with relevant code
π» Code
π Actual behavior
π Expected behavior
I expect
this['a' | 'b']
to bestring | number
in this example, thus accepting the assignment of''
to it, just likeTest['a' | 'b']
.The text was updated successfully, but these errors were encountered: