Skip to content

Commit 3bc97c4

Browse files
authored
Keep original type when using hasProperty if defined (#94)
Keep original type when using hasProperty if defined
1 parent e584d08 commit 3bc97c4

2 files changed

Lines changed: 15 additions & 2 deletions

File tree

src/misc.test-d.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,16 @@ class HasPropertyClassExample {
8989
const hasPropertyClassExample = new HasPropertyClassExample();
9090
hasProperty(hasPropertyClassExample, 'a');
9191

92+
type HasPropertyTypeExample = {
93+
a?: number;
94+
};
95+
96+
// It keeps the original type when defined.
97+
const hasPropertyTypeExample: HasPropertyTypeExample = {};
98+
if (hasProperty(hasPropertyTypeExample, 'a')) {
99+
expectType<number | undefined>(hasPropertyTypeExample.a);
100+
}
101+
92102
//=============================================================================
93103
// RuntimeObject
94104
//=============================================================================

src/misc.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,11 @@ export const hasProperty = <
9393
>(
9494
objectToCheck: ObjectToCheck,
9595
name: Property,
96-
): objectToCheck is ObjectToCheck & Record<Property, unknown> =>
97-
Object.hasOwnProperty.call(objectToCheck, name);
96+
): objectToCheck is ObjectToCheck &
97+
Record<
98+
Property,
99+
Property extends keyof ObjectToCheck ? ObjectToCheck[Property] : unknown
100+
> => Object.hasOwnProperty.call(objectToCheck, name);
98101

99102
export type PlainObject = Record<number | string | symbol, unknown>;
100103

0 commit comments

Comments
 (0)