From e5af1f438d00cd69266034ad2dee508036e4691e Mon Sep 17 00:00:00 2001 From: Maarten Zuidhoorn Date: Tue, 11 Apr 2023 15:03:16 +0200 Subject: [PATCH] Keep original type when using `hasProperty` if defined (#94) Keep original type when using hasProperty if defined --- merged-packages/utils/src/misc.test-d.ts | 10 ++++++++++ merged-packages/utils/src/misc.ts | 7 +++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/merged-packages/utils/src/misc.test-d.ts b/merged-packages/utils/src/misc.test-d.ts index b04d1fe12b..cb0ed77351 100644 --- a/merged-packages/utils/src/misc.test-d.ts +++ b/merged-packages/utils/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/merged-packages/utils/src/misc.ts b/merged-packages/utils/src/misc.ts index 52512ae081..45b7401c7b 100644 --- a/merged-packages/utils/src/misc.ts +++ b/merged-packages/utils/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;