From 415f2aa83b40eae56134d486ee83b43ee426efc9 Mon Sep 17 00:00:00 2001 From: Jonas Daniels Date: Thu, 11 Jan 2024 23:41:28 +1300 Subject: [PATCH] refactor: Simplify deepMerge function and improve type checking (#2151) --- .changeset/curvy-pants-confess.md | 5 +++++ packages/react-native/src/evm/i18n/strings.ts | 1 - .../react-native/src/evm/types/deepPartial.ts | 21 +++++++++++-------- 3 files changed, 17 insertions(+), 10 deletions(-) create mode 100644 .changeset/curvy-pants-confess.md diff --git a/.changeset/curvy-pants-confess.md b/.changeset/curvy-pants-confess.md new file mode 100644 index 00000000000..225926dfe20 --- /dev/null +++ b/.changeset/curvy-pants-confess.md @@ -0,0 +1,5 @@ +--- +"@thirdweb-dev/react-native": patch +--- + +improve typechecking for deepMerge function diff --git a/packages/react-native/src/evm/i18n/strings.ts b/packages/react-native/src/evm/i18n/strings.ts index f7552903c43..07bd72e404e 100644 --- a/packages/react-native/src/evm/i18n/strings.ts +++ b/packages/react-native/src/evm/i18n/strings.ts @@ -36,7 +36,6 @@ export const getLocale = ( return deepMerge(defaultLocale, locale); }; - export const en = (locale?: DeepPartial) => getLocale("en", locale); export const es = (locale?: DeepPartial) => getLocale("es", locale); export const ja = (locale?: DeepPartial) => getLocale("ja", locale); diff --git a/packages/react-native/src/evm/types/deepPartial.ts b/packages/react-native/src/evm/types/deepPartial.ts index 41918134188..cb1a963a12d 100644 --- a/packages/react-native/src/evm/types/deepPartial.ts +++ b/packages/react-native/src/evm/types/deepPartial.ts @@ -2,21 +2,24 @@ export type DeepPartial = { [P in keyof T]?: DeepPartial; }; -export function deepMerge(target: T, source: DeepPartial): T { +export function deepMerge(target: T, source: DeepPartial = {}): T { for (const key in source) { + if (!source.hasOwnProperty(key)) { + continue; + } if ( - source[key] instanceof Object && - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - key in target && - target[key] instanceof Object + isObject(target) && + target.hasOwnProperty(key) && + isObject(target[key]) ) { - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore deepMerge(target[key], source[key]); } else { - target[key] = source[key] as any; + target[key] = source[key] as (typeof target)[typeof key]; } } return target; } + +function isObject(obj: any): obj is object { + return obj !== null && typeof obj === "object"; +}