Skip to content

Commit

Permalink
Keep original type when using hasProperty if defined (MetaMask#94)
Browse files Browse the repository at this point in the history
Keep original type when using hasProperty if defined
  • Loading branch information
Mrtenz authored Apr 11, 2023
1 parent 770e727 commit e5af1f4
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
10 changes: 10 additions & 0 deletions merged-packages/utils/src/misc.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<number | undefined>(hasPropertyTypeExample.a);
}

//=============================================================================
// RuntimeObject
//=============================================================================
Expand Down
7 changes: 5 additions & 2 deletions merged-packages/utils/src/misc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,11 @@ export const hasProperty = <
>(
objectToCheck: ObjectToCheck,
name: Property,
): objectToCheck is ObjectToCheck & Record<Property, unknown> =>
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<number | string | symbol, unknown>;

Expand Down

0 comments on commit e5af1f4

Please sign in to comment.