Skip to content
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

Object#hasOwnProperty and Object.hasOwn are overly restrictive #13

Closed
ehoogeveen-medweb opened this issue Jun 22, 2022 · 1 comment
Closed
Assignees
Labels
bug Something isn't working

Comments

@ehoogeveen-medweb
Copy link

ehoogeveen-medweb commented Jun 22, 2022

In #4 it was suggested to improve the typing to this is this & Record<Key, unknown> but b864600 seems to have set it to something closer to this is {} instead. As a result, none of the properties can queried or assigned to. For example:

const protoObj = { protoProp: 'protoProp' };

const obj: Record<string, string> = Object.create(protoObj);
obj.ownProp = 'ownProp';

for (const key in obj) {
  if (!obj.hasOwnProperty(key)) continue;
  console.log(obj[key]);
}

gives error Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'. (with noImplicitAny enabled). The example is a bit contrived, but this kind of loop is very common in older code where prototypes can't be trusted.

Was the intent to implement something like the intersection suggested in #4? I modified Object.hasOwn locally as follows:

  hasOwn<Obj extends object, Key extends PropertyKey>(
    o: Obj,
    v: Key
  ): o is Obj & (string extends Key
    ? {}
    : number extends Key
    ? {}
    : symbol extends Key
    ? {}
    : Key extends PropertyKey
    ? { [k in Key]: unknown }
    : {})
@uhyo uhyo added the bug Something isn't working label Jul 4, 2022
@uhyo uhyo self-assigned this Jul 4, 2022
@uhyo uhyo closed this as completed in 8dc9dbe Dec 5, 2022
@uhyo
Copy link
Owner

uhyo commented Dec 7, 2022

Thank you, this is fixed in v2.2.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants