Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Created January 26, 2023 17:45
Show Gist options
  • Save yano3nora/41b5a3dafba3927fef83c4966ecd2215 to your computer and use it in GitHub Desktop.
Save yano3nora/41b5a3dafba3927fef83c4966ecd2215 to your computer and use it in GitHub Desktop.
[ts: Object.hasOwn] Force infer object prop with check by Object.hasOwn. #ts
/**
* Force infer object prop with check by Object.hasOwn
*
* @link https://github.com/microsoft/TypeScript/issues/47450#issuecomment-1013737149
* @link https://javascript.plainenglish.io/in-vs-hasown-vs-hasownproperty-in-javascript-885771d2d100
*
* @example
* const myObject = { hello: 'world' }
* const input = prompt('enter key')!
*
* if (objectHas(myObject, input)) {
* console.log(input)
* ~~~~~ infer 'hello'
* }
*/
export const objectHas = <T extends object>(
object: T,
key: string | number | symbol,
): key is keyof T => Object.hasOwn(object, key)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment