Is it possible to create a TypeScript type guard function that determines if a given key is in a given (generic) object — very similar to key in obj, but as a functional type guard (required for reasons unrelated to this question).
For example, something like this:
export function has<T extends { [index: string]: any; [index: number]: any }>(
obj: T,
property: string | symbol | number
): property is keyof T {
return Object.prototype.hasOwnProperty.call(obj, property)
}
// Then in user land somewhere:
interface Foo {
bar: string
}
interface Fuzz {
buzz: string
}
function doWork(thing: Foo | Fuzz) {
if (has(thing, 'bar')) {
alert(thing.bar) // ideally we've type narrowed to know thing contains foo
}
}
The above code does not work how I would expect (alert(thing.foo)) does not know foo exists — obviously my type guard declaration property is keyof T doesn't do what I'm expecting.
You could type guard the results to only be Foo or Fuzz — but I specifically want to type guard that a particular key exists on a generic.