-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
in
operator: check key/property is valid (using keyof
)
#50953
Comments
Note that the |
This is opposite to the highly-requested behavior requested in #21732, which we just implemented const obj = { a: "", b: "" };
if("c" in obj) {
// Works in 4.9 nightly
obj.c
} With exact types we could revisit, but we don't have exact types |
@MartinJohns This suggestion isn't going against that, as far as I can see. The narrowing is useful. I just want TS to check that it's a valid key in at least one of the union members, so I can't make silly mistakes. @RyanCavanaugh I think #21732 is really useful, when we're dealing with a type like |
If the object isn't aliased in some way, why are you writing an |
Here's one example: type Fish = { swim: () => void };
type Bird = { fly: () => void };
type Human = { swim?: () => void; fly?: () => void };
const getType = (animal: Fish | Bird | Human) => {
// oops, typo!
if ("flyyy" in animal) {
return "bird";
} else {
return "other";
}
}; |
You explicitly mentioned |
You're right. I should have said something like "distributive |
Sure, but what you're proposing breaks subtyping linearity: if If you had written type Fish = { swim: () => void };
type Bird = { fly: () => void };
type Human = { swim?: () => void; fly?: () => void };
const getType = (animal: Fish | Bird | Human) => {
if ("superman" in animal) {
return "kryptonian";
} else {
return "earthling";
}
}; there doesn't seem to be an error in this program. |
@OliverJAsh You could probably easily write an ESLint rule for this, if you still want it. |
Can you explain why? |
Suggestion
π Search Terms
β Viability Checklist
My suggestion meets these guidelines:
β Suggestion
When using the
in
operatorK in T
, TypeScript should error if the provided keyK
is not assignable tokeyof T
.π Motivating Example
π» Use Cases
I've tried to define a
has
function for this purpose but there are lots of edge cases: https://stackoverflow.com/questions/58749852/typescript-defining-the-in-operator-as-a-functionThe text was updated successfully, but these errors were encountered: