Given a certain interface
interface Bar {
bar?: string
}
Is there a way to make the hasOwnProperty method check the property against the defined interface?
const b: Bar = { bar: 'b' }
b.hasOwnProperty('bar') // works as expected
b.hasOwnProperty('ba') // wish this would throw an error saying "ba" does not exist in Bar
I have thought about using
b.bar !== undefined
but this is not exactly the same since theoretically bar
could exist but be assigned to undefined, like so:
const b: Bar = { bar: undefined }
b.hasOwnProperty('bar') // true
b.bar !== undefined // false
I realize I could create my own function that wraps hasOwnProperty with the correct type signature such as
has<T extends object>(obj: T, key: keyof T): boolean
, but I am curious if there is a more built-in alternative.