简体   繁体   中英

How to write a Typescript hasOwnProperty type guard that accepts any input?

This is mostly just to learn how TS works. Here's 2 ways I can write a type guard for hasOwnProperty:

function hasOwnProperty<
  Obj extends Record<string, any>,
  Prop extends any,
>(
  obj: Obj,
  prop: Prop,
): prop is keyof Obj {
  return Object.prototype.hasOwnProperty.call(obj, prop as any);
}

Error: Type 'keyof Obj' is not assignable to type 'Prop'.

function hasOwnProperty<
  Obj extends Record<string, any>,
  Prop extends any,
>(
  obj: Obj,
  prop: Prop,
): obj is Obj & Record<Prop, any> {
  return Object.prototype.hasOwnProperty.call(obj, prop as any);
}

Error: Type 'Prop' does not satisfy the constraint 'string | number | symbol'. Type 'Prop' does not satisfy the constraint 'string | number | symbol'.

If I want prop to be any , is there a way to make this work?

You can define a class (let say Test ) and use it in this way prop is keyof Test

class Test{

}

function hasOwnProperty<
  Obj extends Record<string, any>,
  Prop extends any,
>(
  obj: Obj,
  prop: Prop,
): prop is keyof Test {
  return Object.prototype.hasOwnProperty.call(obj, prop as any);
}

PlaygroundLink

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM