-
Notifications
You must be signed in to change notification settings - Fork 12.5k
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
Improve Object.hasOwn #58877
Comments
I don't think it's a good idea. function Object_hasOwn<T extends object = object>(o: T, v: PropertyKey): v is keyof T {
return Object.hasOwn(o, v);
}
declare const x: { a: 1 } | { b: 2 }
const prop: string = 'a';
if (Object_hasOwn(x, prop)) {
prop
// ^? prop: never... what?
} |
Hmmm.
If you use a const instead of a function Object_hasOwn<T extends object = object>(
o: T,
v: PropertyKey
): v is keyof T {
return Object.hasOwn(o, v);
}
const x: {a: 1} | {b: 2} = {a: 1};
const prop: string = 'a';
if (Object_hasOwn(x, prop)) {
prop;
// ^? prop: "a"
} |
Duplicate of #44253. |
For future reference, this is not true. Even with one-way type predicates, this wouldn't be sound for excess properties: |
⚙ Compilation target
esnext
⚙ Library
esnext
Missing / Incorrect Definition
Object.hasOwn
:Requested:
hasOwn(o: object, v: PropertyKey): boolean;
→hasOwn<T extends object = object>(o: T, v: PropertyKey): v is keyof T>;
To my understanding, a type predicate only asserts one way, so this should be sound even if there are excess properties.
As far as I can tell, this shouldn't be breaking.
Right now, I have a helper function that asserts this, but copying it into every project gets annoying and repetitive.
Sample Code
Documentation Link
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn
The text was updated successfully, but these errors were encountered: