diff --git a/src/misc.test-d.ts b/src/misc.test-d.ts index b04d1fe1..cb0ed773 100644 --- a/src/misc.test-d.ts +++ b/src/misc.test-d.ts @@ -89,6 +89,16 @@ class HasPropertyClassExample { const hasPropertyClassExample = new HasPropertyClassExample(); hasProperty(hasPropertyClassExample, 'a'); +type HasPropertyTypeExample = { + a?: number; +}; + +// It keeps the original type when defined. +const hasPropertyTypeExample: HasPropertyTypeExample = {}; +if (hasProperty(hasPropertyTypeExample, 'a')) { + expectType(hasPropertyTypeExample.a); +} + //============================================================================= // RuntimeObject //============================================================================= diff --git a/src/misc.ts b/src/misc.ts index 52512ae0..45b7401c 100644 --- a/src/misc.ts +++ b/src/misc.ts @@ -93,8 +93,11 @@ export const hasProperty = < >( objectToCheck: ObjectToCheck, name: Property, -): objectToCheck is ObjectToCheck & Record => - Object.hasOwnProperty.call(objectToCheck, name); +): objectToCheck is ObjectToCheck & + Record< + Property, + Property extends keyof ObjectToCheck ? ObjectToCheck[Property] : unknown + > => Object.hasOwnProperty.call(objectToCheck, name); export type PlainObject = Record;