microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
101.02k stars 12.49k forks source link

Support for `Object.hasOwn` (`lib.d.ts` and narrowing) #44253

Open DanielRosenwasser opened 3 years ago

DanielRosenwasser commented 3 years ago

Object.hasOwn(obj, key) has just moved to stage 3.

https://github.com/tc39/proposal-accessible-object-hasownproperty

RyanCavanaugh commented 3 years ago

Discussed a bit with @jamiebuilds offline. Some key scenarios and questions to resolve:

declare const ra: Record<string, any>;
if (Object.hasOwn(ra, "foo")) {
  ra.foo; // should be 'any'
}

declare const ru: Record<string, unknown>;
if (Object.hasOwn(ra, "foo")) {
  ra.foo; // should be 'unknown'
}

declare const abcd: { a: string, b: string } | { c: string, d: string };
if (Object.hasOwn(abcd, "a")) {
  abcd.b; // should be OK
}
// Should this be OK?
// Could argue either way
Object.hasOwn(abcd, "efg")

// TODO: Add more use cases + desired behavior
DanielRosenwasser commented 3 years ago

Should there be a separate issue for hasOwn guards? Should it continue here? Doesn't https://github.com/microsoft/TypeScript/pull/43947 already hande hasOwnProperty specially?

DanielRosenwasser commented 3 years ago
declare const abcd: { a: string, b: string } | { c: string, d: string };
if (Object.hasOwn(abcd, "a")) {
  abcd.b; // should be OK
}

I don't like it, but we already did it for in.

I think one concern I have is making sure that the else branch doesn't narrow out anything that does have that property. Specifically this:

declare const abcd: { a: string, b: string } | { c: string, d: string };
if ("a" in abcd) {
    abcd.b; // okay
}
else {
    abcd.c // okay
    abcd.d // okay
}

in currently does a negated narrowing because of the prototype walk, but hasOwn won't. In theory, it would be more correct to keep the type of abcd as { a: string, b: string } | { c: string, d: string } in the else branch. But maybe that's too pedantic.

pubmikeb commented 3 years ago

Object.hasOwn has reached stage 4 and is finally in GA of V8/Chromium-based browsers/Node.js. It's a time to update lib.es5.d.ts.

pubmikeb commented 3 years ago

Any update? Both, Node.js v.16.11+ and V8 v.95+ support Object.hasOwn out-of-box.

P.S. On 17th October Node.js 17.0 will be released.

nicolas377 commented 2 years ago

Since there doesn't seem to be much progress here, could I help with this in any way?

r-cyr commented 2 years ago

This feature is, AFAIK, now Stage 4 and scheduled to be part of this June release of ES2022. It would be wonderful if it could do narrowing, because I wouldn't be surprised if it will eventually replace most usages of Object#hasOwnProperty(hasOwn is safer) and the in operator(hasOwn doesn't have to go through the prototype chain).

devinrhode2 commented 2 years ago

fp-ts has a totally good implementation: https://github.com/gcanti/fp-ts/blob/2.11.9/src/ReadonlyRecord.ts#L249 Could probably just copy it verbatim, it's pretty good.

devinrhode2 commented 2 years ago

I'm using this, I suggest others try it out and if there are no issues, we merge this baby :)

export const hasOwn = <RecordKeys extends string>(
  record: Readonly<Record<RecordKeys, unknown>>,
  key: string,
): key is RecordKeys => {
  return Object.prototype.hasOwnProperty.call(record, key)
}

(PS I basically copied from fp-ts has function)

jamiebuilds commented 2 years ago

@devinrhode2 That approach has a lot of flaws

This is the current definition I'm using:

export type SetRequired<BaseType, Keys extends keyof BaseType> = 
    BaseType &
    Omit<BaseType, Keys> &
    Required<Pick<BaseType, Keys>>;

interface ObjectConstructor {
    hasOwn<BaseType, Key extends keyof BaseType>(record: BaseType, key: Key): record is SetRequired<BaseType, Key>
    hasOwn<Key extends PropertyKey>(record: object, key: Key): record is { [K in Key]: unknown }
}

Edit: More complete cases

devinrhode2 commented 2 years ago

hmm... not working in the one case I'd like it to work

let role = 'adsf' as string
const rolesConst = {
    'admin': 'admin',
    'user': 'user'
} as const
if (!Object.hasOwn(rolesConst, role)) {
    throw new Error('Unknown role: ' + role)
}
role // Should be `keyof typeof rolesConst`, not `string` :)

// assert<IsEqual<typeof role, keyof typeof rolesConst>>()
jamiebuilds commented 2 years ago

@devinrhode2 If you make role a const or if you type it to be keyof typeof rolesConst it will work. So overall it can still cover more cases

devinrhode2 commented 2 years ago

It's a String coming over the wire, so neither of those options work :(

The goal is to verify the given role is known, to act as a type guard, to narrow the type

devinrhode2 commented 2 years ago

Maybe the fp-ts version should require the object to look like a const (have "readonly" modifiers)

And it doesn't look like a const, recommend using your version?

How could we get the best of both worlds?!

devinrhode2 commented 2 years ago

Actually, as strange as it is, I am actually going to tweak the fp-ts type a little, for key I am going to accept any. Because, in my case, a "string" coming over the wire could actually shake out to be a number for all I know.

export const hasOwn = <RecordKeys extends string>(
  record: Readonly<Record<RecordKeys, unknown>>,
  // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
  key: any,
): key is RecordKeys => {
  return Object.prototype.hasOwnProperty.call(record, key)
}

CleanShot 2022-04-15 at 11 57 45 (forgot boolean in that screenshot, but it also works fine, just returns false like the others)

devinrhode2 commented 2 years ago

This allows me to both cleanup type-guards before calling hasOwn (I don't need to ensure it's a 'string' type) and encourages callers to just pass in anything. Because any nonsense will get caught and/or filtered out.

nicolas377 commented 2 years ago

Is there a benefit to using any instead of unknown? I'm fairly confident they're the same type, but unknown is generally preferred to any. I'm not completely sure if there's already precedent here for using any though.

devinrhode2 commented 2 years ago

When I'm passing a parameter into this util, the type is unknown, I find it's actually useful since it's data coming over the wire, I the type actually is unknown to me, and typing it as such ensures I handle all the respective edge cases.

I recall trying to use unknown first but maybe I was getting a type error on the return type, that unknown was not assignable to Property keys iirc? Or maybe on hasOwnProperty.call... Anyway, I found any was preferable, you literally can pass anything into hasOwnProperty and it gives a correct return value.

nicolas377 commented 2 years ago

Here's a playground with a possible implementation. The implementation is just @devinrhode2's tweaked version plugged into the ObjectConstructor interface. I did change it to accept unknown instead of any, it doesn't seem to have any effect.

devinrhode2 commented 2 years ago

Just for good measure, I really just copied source from fp-ts project. Actually the type guard there was originally implemented in this PR: https://github.com/gcanti/fp-ts/pull/1075 by @gcanti

As such I think it'd be good to seek a "thumbs up" or "lgtm" from @gcanti before this slips into core :)

devinrhode2 commented 2 years ago

@jamiebuilds is there a better way to write the code snippet I provided?

  1. Given a list of known good user roles (const array/object/enum: rolesConst)
  2. Check if an unknown string role is part of this list (has(rolesConst, role), rolesConst[role] !== undefined, role in rolesConst)
  3. If it's part of this list, the type should be a union of the known good user role names

I did experiment briefly with a const array approach but opted to go with const object instead because i liked being able to write code like:

if (role === rolesConst.admin) { ...yay }

As opposed to:

if (role === rolesConst[2]) { ...ew }

Maybe this is an edge case where a const enum would be useful, idk.

=====

Did some hacking on the test cases, was able to add a few failing test cases for narrowing of a string key (2nd argument) passed in.

nicolas377 commented 2 years ago

Another idea I've had is that if/when #49220 or #33471 become reality, the Object.hasOwn type can use unknown | RecordKeys to suggest through intellisense that the inputted key be a member of RecordKeys, but still support narrowing the type of key.

jumoog commented 2 years ago

ES2022 has Object.hasOwn support

nicolas377 commented 2 years ago

I'm happy to PR in this implementation (i added my narrowing implementation on top of the current base) if the maintainers are wanting it.

devinrhode2 commented 2 years ago

@nicolas377 doesn't pass as many test cases as my last example

But, idk how valuable these test cases are, it's been a minute, and I didn't originally write them. Regardless, I assume we want to get as many of those passing as possible. When I swap in your implementation, it goes from 8 failing tests to 27 :(

Joshuaweiss commented 2 years ago

Wouldn't we need something like better excess property checks on unions here otherwise you could do:

const result: { a: string } | { b: string, c: string } = { a: '', b: '' }
if (Object.hasOwn(result, "b")) {
  result.c; // should NOT be ok
}

Although it seems to mention already in regards to in https://github.com/microsoft/TypeScript/issues/20863

ziloen commented 2 years ago

Try this one:

/** Extract from T those types that has K keys  */
type ExtractByKey<T, K extends keyof any> =
  T extends infer R
    ? K extends keyof R
      ? R
      : never
    : never

type KeyofUnion<T> = T extends infer R ? keyof R : never

declare global {
  interface ObjectConstructor {
    /**
     * Determines whether an object has a property with the specified name.
     * @param o An object.
     * @param v A property name.
     */
    hasOwn<T extends Record<keyof any, any>, K extends keyof any>(
      o: T,
      v: K
    ): o is K extends KeyofUnion<T> ? ExtractByKey<T, K> : T & { [P in K]: unknown }
  }
}

If you want the key to be required:

type RequiredByKey<T, K extends keyof T> = { [P in K]-?: T[P] } & { [P in Exclude<keyof T, K>]: T[P] }

type ExtractAndRequiredByKey<T, K extends keyof any> =
  T extends infer R
    ? K extends keyof R
      ? RequiredByKey<R, K>
      : never
    : never

declare global {
  interface ObjectConstructor {
    hasOwn<T extends Record<keyof any, any>, K extends keyof any>(
      o: T,
      v: K
      // @ts-expect-error I don't know how to fix this error 😥
    ): o is K extends KeyofUnion<T> ? ExtractAndRequiredByKey<T, K> : T & { [P in K]: unknown }
  }
}
flevi29 commented 11 months ago

So to clarify to myself and others a thing or two:

So, this hasn't been revisited for 2.5 years and probably won't be for the foreseeable future (it's a very nuanced and tricky thing to solve correctly, I'm not blaming anyone). So what does that leave us with, what's the best practice?

devinrhode2 commented 11 months ago

Totally guessing, but it's probably due to its unique syntax

On Tue, Dec 12, 2023 at 5:36 AM F. Levi @.***> wrote:

So to clarify to myself and others a thing or two:

— Reply to this email directly, view it on GitHub https://github.com/microsoft/TypeScript/issues/44253#issuecomment-1851865834, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAEDZKHBJZUKPTIXAL253SDYJA6S5AVCNFSM45P6SZZ2U5DIOJSWCZC7NNSXTN2JONZXKZKDN5WW2ZLOOQ5TCOBVGE4DMNJYGM2A . You are receiving this because you were mentioned.Message ID: @.***>

nicolas377 commented 10 months ago

It's been a hot second since I've touched typescript, but looking back through this issue, I think it'd be great to have an open discussion about what Object.hasOwn should look like in ts. It's obviously becoming more and more popular, and the current implementation leaves almost everything up to the end user for them to cast narrow, so I think narrowing should be part of the core implementation of hasOwn.

I have two questions:

  1. How bulky is too bulky of a type implementation? We could end up running into some pretty complex scenarios, especially with security concerns that may be raised based on different use cases of ts, so what's it gonna take for this to get merged into core?
  2. Where's a good place to have a discussion about this implementation? I'd love for as many people as possible to share their uses of hasOwn so we can account for them in testing.

p.s. I'm a senior in high school, and I won't be working on this a lot come spring semester, so I'd love for a maintainer to pick this up before I disappear back into my academic hole, so I'm mostly trying to kick this discussion off, because I'd love to see hasOwn supported.

furkanmustafa commented 3 months ago
// https://github.com/microsoft/TypeScript/issues/1260#issuecomment-1288111146
// Creates a union of all keys of all objects in the Terface union
type AllKeys<Terface> = Terface extends any ? (keyof Terface & (string | number | symbol)) : never;
// Creates a new interface adding the missing keys to Terface
type Wrap<Terface, Keys extends string | number | symbol> = (Terface & {
  [K in Exclude<Keys, keyof Terface>]?: undefined;
});
// Distributes the union and automatically add the missing keys
type NicerUndefineds<Terface, Keys extends AllKeys<Terface> = AllKeys<Terface>> = Terface extends any ? Wrap<Terface, Keys> : never;

declare global {
  interface ObjectConstructor {
    hasOwn<
      K extends string|number|symbol,
      O extends Record<any, any>,
      OK extends NicerUndefineds<O> extends { [k in K]?: infer VType }
        ? { [k in K]: VType } & O : { [k in K]: unknown } & O,
    >(obj: O, k: K): obj is OK;
  }
}

I'm seriously tired of all of these. Finally I can proceed with my day. (I forgot what I was originally working on)

Thank you too.

viktor-urbanas-qatalog commented 3 months ago

any progress on this?

KisaragiEffective commented 3 months ago

I believe this awaits someone's PR, right?

nicolas377 commented 3 months ago

Yes, we're awaiting a PR. This is a pretty complicated problem to solve, as you may have noticed from the discussions above. There are a couple of proposed solutions, but I think it'd be a good idea to gather use/test cases for .hasOwn() and build the definition off of that. That's my opinion though. I'm unable to contribute at the moment, but I'll get some more time soon, and I'll definitely be returning here.

furkanmustafa commented 3 months ago

@furkanmustafa

Thank you too.

Actually "no thank you" to me. My code doesn't satisty most of the requirements demanded here.

My latest tests confirm that the second implementation by @ziloen above makes all of the tests happy.

Tested every case stated above. Also tested a rather large codebase in our project. All works fine.

Last question would be, how to solve the sad ts-expect-error mark there.

image
carafelix commented 2 months ago

There is yet no PR addressing the issue? Currently there is no type inference after the use of hasOwn

Object.hasOwn(obj, "prefix") && obj.prefix // <---- still not being inferred as a valid key