From 65dd104fd2f4ac5879f96786be43a4341058b476 Mon Sep 17 00:00:00 2001 From: Jacob Pihl Date: Fri, 22 Nov 2024 15:32:13 +0100 Subject: [PATCH] Type guard the middleware action MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit To tighten the type safety for ´extractServiceBaseUrls´ we validate the incoming action against a type guard --- .../reduxMiddleware/extractServiceBaseUrls.ts | 23 +++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/src/core/utils/reduxMiddleware/extractServiceBaseUrls.ts b/src/core/utils/reduxMiddleware/extractServiceBaseUrls.ts index 26fc53845d..9832381d2e 100644 --- a/src/core/utils/reduxMiddleware/extractServiceBaseUrls.ts +++ b/src/core/utils/reduxMiddleware/extractServiceBaseUrls.ts @@ -17,6 +17,13 @@ export type ServiceBaseUrls = | Record | Record; +type Action = { + type: string; + payload: { + entries: ServiceBaseUrls; + }; +}; + type ServiceBaseUrlKey = keyof ServiceBaseUrls; export const serviceUrlKeys = { @@ -43,15 +50,23 @@ const filterUrls = ( return { ...obj, ...{ [key]: urls[key as Api] } }; }, {}); +// Type guard Action +const isAction = (action: any): action is Action => { + return ( + action && + action.type === "url/addUrlEntries" && + action.payload && + typeof action.payload.entries === "object" + ); +}; + // Redux middleware that extracts the service base urls from the action // and stores them in the serviceBaseUrls "store". const extractServiceBaseUrls: Middleware< Record, EnhancedStore - // we need to use any here because we don't know the action type - // eslint-disable-next-line @typescript-eslint/no-explicit-any -> = () => (next) => (action: any) => { - if (String(action.type) === "url/addUrlEntries") { +> = () => (next) => (action) => { + if (isAction(action)) { const { payload: { entries } } = action;