From 1330842a843139b2a122db926e3c2781decdb164 Mon Sep 17 00:00:00 2001 From: Chirag Chandrakant Salian Date: Fri, 24 May 2024 15:47:32 -0700 Subject: [PATCH] Revert "[No QA] Enable `no-unsafe-argument` eslint rule" --- .eslintrc.js | 1 + .../javascript/bumpVersion/bumpVersion.ts | 11 +++-------- .github/actions/javascript/bumpVersion/index.js | 5 +---- .../checkDeployBlockers/checkDeployBlockers.ts | 2 +- .../getGraphiteString/getGraphiteString.ts | 2 +- .../getPreviousVersion/getPreviousVersion.ts | 9 ++------- .../javascript/getPreviousVersion/index.js | 5 +---- .../reviewerChecklist/reviewerChecklist.ts | 2 +- .github/scripts/detectRedirectCycle.ts | 2 +- desktop/contextBridge.ts | 2 +- desktop/main.ts | 4 ++-- .../AttachmentPicker/index.native.tsx | 4 ++-- .../Attachments/AttachmentCarousel/index.tsx | 5 ++--- src/components/Composer/index.tsx | 2 +- src/components/Icon/__mocks__/Expensicons.ts | 5 +---- src/components/OfflineWithFeedback.tsx | 8 +++----- src/components/Onfido/BaseOnfidoWeb.tsx | 5 ++--- src/components/Onfido/index.native.tsx | 7 +++---- .../ProfilingToolMenu/BaseProfilingToolMenu.tsx | 2 +- .../SignInButtons/AppleSignIn/index.android.tsx | 6 +++--- .../SignInButtons/AppleSignIn/index.ios.tsx | 7 +++---- src/libs/EmojiUtils.ts | 10 ++++------ .../Environment/betaChecker/index.android.ts | 2 +- src/libs/Localize/index.ts | 2 +- src/libs/Middleware/Logging.ts | 7 +++---- .../LocalNotification/BrowserNotifications.ts | 2 +- .../PushNotification/index.native.ts | 2 +- src/libs/Pusher/pusher.ts | 12 ++++-------- src/libs/actions/Device/index.ts | 2 +- .../report/ContextMenu/ContextMenuActions.tsx | 2 +- .../ComposerWithSuggestions.tsx | 9 ++------- src/pages/home/report/ReportActionsList.tsx | 4 ++-- .../step/IOURequestStepScan/index.native.tsx | 6 +++--- tests/e2e/server/index.ts | 2 +- tests/ui/UnreadIndicatorsTest.tsx | 8 ++------ tests/unit/MiddlewareTest.ts | 8 ++++---- tests/unit/markPullRequestsAsDeployedTest.ts | 6 +++--- tests/utils/TestHelper.ts | 4 ++-- tests/utils/collections/reportActions.ts | 17 +++++++++-------- workflow_tests/utils/ExtendedAct.ts | 4 ++-- workflow_tests/utils/preGenerateTest.ts | 8 +++----- 41 files changed, 86 insertions(+), 127 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index eb50d1fcc5f3..1f23ae22ca7e 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -100,6 +100,7 @@ module.exports = { __DEV__: 'readonly', }, rules: { + '@typescript-eslint/no-unsafe-argument': 'off', '@typescript-eslint/no-unsafe-call': 'off', '@typescript-eslint/no-unsafe-member-access': 'off', '@typescript-eslint/no-unsafe-assignment': 'off', diff --git a/.github/actions/javascript/bumpVersion/bumpVersion.ts b/.github/actions/javascript/bumpVersion/bumpVersion.ts index eba79c7c9edb..ed4828367cf2 100644 --- a/.github/actions/javascript/bumpVersion/bumpVersion.ts +++ b/.github/actions/javascript/bumpVersion/bumpVersion.ts @@ -1,7 +1,6 @@ import * as core from '@actions/core'; import {exec as originalExec} from 'child_process'; import fs from 'fs'; -import type {PackageJson} from 'type-fest'; import {promisify} from 'util'; import {generateAndroidVersionCode, updateAndroidVersion, updateiOSVersion} from '@github/libs/nativeVersionUpdater'; import * as versionUpdater from '@github/libs/versionUpdater'; @@ -20,7 +19,7 @@ function updateNativeVersions(version: string) { .then(() => { console.log('Successfully updated Android!'); }) - .catch((err: string | Error) => { + .catch((err) => { console.error('Error updating Android'); core.setFailed(err); }); @@ -48,12 +47,8 @@ if (!semanticVersionLevel || !Object.keys(versionUpdater.SEMANTIC_VERSION_LEVELS console.log(`Invalid input for 'SEMVER_LEVEL': ${semanticVersionLevel}`, `Defaulting to: ${semanticVersionLevel}`); } -const {version: previousVersion}: PackageJson = JSON.parse(fs.readFileSync('./package.json').toString()); -if (!previousVersion) { - core.setFailed('Error: Could not read package.json'); -} - -const newVersion = versionUpdater.incrementVersion(previousVersion ?? '', semanticVersionLevel); +const {version: previousVersion} = JSON.parse(fs.readFileSync('./package.json').toString()); +const newVersion = versionUpdater.incrementVersion(previousVersion, semanticVersionLevel); console.log(`Previous version: ${previousVersion}`, `New version: ${newVersion}`); updateNativeVersions(newVersion); diff --git a/.github/actions/javascript/bumpVersion/index.js b/.github/actions/javascript/bumpVersion/index.js index e1a5cf13a8d9..d4a085fc9ddf 100644 --- a/.github/actions/javascript/bumpVersion/index.js +++ b/.github/actions/javascript/bumpVersion/index.js @@ -3478,10 +3478,7 @@ if (!semanticVersionLevel || !Object.keys(versionUpdater.SEMANTIC_VERSION_LEVELS console.log(`Invalid input for 'SEMVER_LEVEL': ${semanticVersionLevel}`, `Defaulting to: ${semanticVersionLevel}`); } const { version: previousVersion } = JSON.parse(fs_1.default.readFileSync('./package.json').toString()); -if (!previousVersion) { - core.setFailed('Error: Could not read package.json'); -} -const newVersion = versionUpdater.incrementVersion(previousVersion ?? '', semanticVersionLevel); +const newVersion = versionUpdater.incrementVersion(previousVersion, semanticVersionLevel); console.log(`Previous version: ${previousVersion}`, `New version: ${newVersion}`); updateNativeVersions(newVersion); console.log(`Setting npm version to ${newVersion}`); diff --git a/.github/actions/javascript/checkDeployBlockers/checkDeployBlockers.ts b/.github/actions/javascript/checkDeployBlockers/checkDeployBlockers.ts index d51d68796070..bf94b136ce43 100644 --- a/.github/actions/javascript/checkDeployBlockers/checkDeployBlockers.ts +++ b/.github/actions/javascript/checkDeployBlockers/checkDeployBlockers.ts @@ -60,7 +60,7 @@ const run = function (): Promise { core.setOutput('HAS_DEPLOY_BLOCKERS', false); } }) - .catch((error: string | Error) => { + .catch((error) => { console.error('A problem occurred while trying to communicate with the GitHub API', error); core.setFailed(error); }); diff --git a/.github/actions/javascript/getGraphiteString/getGraphiteString.ts b/.github/actions/javascript/getGraphiteString/getGraphiteString.ts index c486fdbd39f3..57a941105f90 100644 --- a/.github/actions/javascript/getGraphiteString/getGraphiteString.ts +++ b/.github/actions/javascript/getGraphiteString/getGraphiteString.ts @@ -28,7 +28,7 @@ const run = () => { // Extract timestamp, Graphite accepts timestamp in seconds if (current.metadata?.creationDate) { - timestamp = Math.floor(new Date(current.metadata.creationDate as string).getTime() / 1000); + timestamp = Math.floor(new Date(current.metadata.creationDate).getTime() / 1000); } if (current.name && current.meanDuration && current.meanCount && timestamp) { diff --git a/.github/actions/javascript/getPreviousVersion/getPreviousVersion.ts b/.github/actions/javascript/getPreviousVersion/getPreviousVersion.ts index 262b603124fa..dc1e99d1e3b8 100644 --- a/.github/actions/javascript/getPreviousVersion/getPreviousVersion.ts +++ b/.github/actions/javascript/getPreviousVersion/getPreviousVersion.ts @@ -1,6 +1,5 @@ import * as core from '@actions/core'; import {readFileSync} from 'fs'; -import type {PackageJson} from 'type-fest'; import * as versionUpdater from '@github/libs/versionUpdater'; const semverLevel = core.getInput('SEMVER_LEVEL', {required: true}); @@ -8,10 +7,6 @@ if (!semverLevel || !Object.values(versionUpdater.SEMANTIC_VERSION_LEVEL core.setFailed(`'Error: Invalid input for 'SEMVER_LEVEL': ${semverLevel}`); } -const {version: currentVersion}: PackageJson = JSON.parse(readFileSync('./package.json', 'utf8')); -if (!currentVersion) { - core.setFailed('Error: Could not read package.json'); -} - -const previousVersion = versionUpdater.getPreviousVersion(currentVersion ?? '', semverLevel); +const {version: currentVersion} = JSON.parse(readFileSync('./package.json', 'utf8')); +const previousVersion = versionUpdater.getPreviousVersion(currentVersion, semverLevel); core.setOutput('PREVIOUS_VERSION', previousVersion); diff --git a/.github/actions/javascript/getPreviousVersion/index.js b/.github/actions/javascript/getPreviousVersion/index.js index 8eac2f62f03e..f372f0fdaf99 100644 --- a/.github/actions/javascript/getPreviousVersion/index.js +++ b/.github/actions/javascript/getPreviousVersion/index.js @@ -2728,10 +2728,7 @@ if (!semverLevel || !Object.values(versionUpdater.SEMANTIC_VERSION_LEVELS).inclu core.setFailed(`'Error: Invalid input for 'SEMVER_LEVEL': ${semverLevel}`); } const { version: currentVersion } = JSON.parse((0, fs_1.readFileSync)('./package.json', 'utf8')); -if (!currentVersion) { - core.setFailed('Error: Could not read package.json'); -} -const previousVersion = versionUpdater.getPreviousVersion(currentVersion ?? '', semverLevel); +const previousVersion = versionUpdater.getPreviousVersion(currentVersion, semverLevel); core.setOutput('PREVIOUS_VERSION', previousVersion); diff --git a/.github/actions/javascript/reviewerChecklist/reviewerChecklist.ts b/.github/actions/javascript/reviewerChecklist/reviewerChecklist.ts index f57ef6c36a04..aabc6b33086a 100644 --- a/.github/actions/javascript/reviewerChecklist/reviewerChecklist.ts +++ b/.github/actions/javascript/reviewerChecklist/reviewerChecklist.ts @@ -90,7 +90,7 @@ function checkIssueForCompletedChecklist(numberOfChecklistItems: number) { getNumberOfItemsFromReviewerChecklist() .then(checkIssueForCompletedChecklist) - .catch((err: string | Error) => { + .catch((err) => { console.error(err); core.setFailed(err); }); diff --git a/.github/scripts/detectRedirectCycle.ts b/.github/scripts/detectRedirectCycle.ts index 6da0ecba158c..5aa0d1daf342 100644 --- a/.github/scripts/detectRedirectCycle.ts +++ b/.github/scripts/detectRedirectCycle.ts @@ -52,7 +52,7 @@ function detectCycle(): boolean { fs.createReadStream(`${process.cwd()}/docs/redirects.csv`) .pipe(parser) - .on('data', (row: [string, string]) => { + .on('data', (row) => { // Create a directed graph of sourceURL -> targetURL addEdge(row[0], row[1]); }) diff --git a/desktop/contextBridge.ts b/desktop/contextBridge.ts index 61ede178da2d..487e528a7485 100644 --- a/desktop/contextBridge.ts +++ b/desktop/contextBridge.ts @@ -67,7 +67,7 @@ contextBridge.exposeInMainWorld('electron', { } // Deliberately strip event as it includes `sender` - ipcRenderer.on(channel, (event, ...args: unknown[]) => func(...args)); + ipcRenderer.on(channel, (event, ...args) => func(...args)); }, /** Remove listeners for a single channel from the main process and sent to the renderer process. */ diff --git a/desktop/main.ts b/desktop/main.ts index 64587f42bf56..b40557464ec1 100644 --- a/desktop/main.ts +++ b/desktop/main.ts @@ -581,7 +581,7 @@ const mainWindow = (): Promise => { app.hide(); } - ipcMain.on(ELECTRON_EVENTS.LOCALE_UPDATED, (event, updatedLocale: Locale) => { + ipcMain.on(ELECTRON_EVENTS.LOCALE_UPDATED, (event, updatedLocale) => { Menu.setApplicationMenu(Menu.buildFromTemplate(localizeMenuItems(initialMenuTemplate, updatedLocale))); disposeContextMenu(); disposeContextMenu = createContextMenu(updatedLocale); @@ -601,7 +601,7 @@ const mainWindow = (): Promise => { // Listen to badge updater event emitted by the render process // and update the app badge count (MacOS only) - ipcMain.on(ELECTRON_EVENTS.REQUEST_UPDATE_BADGE_COUNT, (event, totalCount?: number) => { + ipcMain.on(ELECTRON_EVENTS.REQUEST_UPDATE_BADGE_COUNT, (event, totalCount) => { if (totalCount === -1) { // The electron docs say you should be able to update this and pass no parameters to set the badge // to a single red dot, but in practice it resulted in an error "TypeError: Insufficient number of diff --git a/src/components/AttachmentPicker/index.native.tsx b/src/components/AttachmentPicker/index.native.tsx index 218a255d34d3..ad4cf023c096 100644 --- a/src/components/AttachmentPicker/index.native.tsx +++ b/src/components/AttachmentPicker/index.native.tsx @@ -171,7 +171,7 @@ function AttachmentPicker({type = CONST.ATTACHMENT_PICKER_TYPE.FILE, children, s */ const showDocumentPicker = useCallback( (): Promise => - RNDocumentPicker.pick(getDocumentPickerOptions(type)).catch((error: Error) => { + RNDocumentPicker.pick(getDocumentPickerOptions(type)).catch((error) => { if (RNDocumentPicker.isCancel(error)) { return; } @@ -247,7 +247,7 @@ function AttachmentPicker({type = CONST.ATTACHMENT_PICKER_TYPE.FILE, children, s .then((result) => { completeAttachmentSelection.current(result); }) - .catch((error: Error) => { + .catch((error) => { showGeneralAlert(error.message); throw error; }); diff --git a/src/components/Attachments/AttachmentCarousel/index.tsx b/src/components/Attachments/AttachmentCarousel/index.tsx index 42536ae208ae..3a7e0f19c4cd 100644 --- a/src/components/Attachments/AttachmentCarousel/index.tsx +++ b/src/components/Attachments/AttachmentCarousel/index.tsx @@ -92,14 +92,13 @@ function AttachmentCarousel({report, reportActions, parentReportActions, source, return; } - const item: Attachment = entry.item; if (entry.index !== null) { setPage(entry.index); - setActiveSource(item.source); + setActiveSource(entry.item.source); } if (onNavigate) { - onNavigate(item); + onNavigate(entry.item); } }, [isFullScreenRef, onNavigate], diff --git a/src/components/Composer/index.tsx b/src/components/Composer/index.tsx index f8bff00f3689..4bc54d13b056 100755 --- a/src/components/Composer/index.tsx +++ b/src/components/Composer/index.tsx @@ -122,7 +122,7 @@ function Composer( if (shouldCalculateCaretPosition && isRendered) { // we do flushSync to make sure that the valueBeforeCaret is updated before we calculate the caret position to receive a proper position otherwise we will calculate position for the previous state flushSync(() => { - setValueBeforeCaret((webEvent.target as HTMLInputElement).value.slice(0, webEvent.nativeEvent.selection.start)); + setValueBeforeCaret(webEvent.target.value.slice(0, webEvent.nativeEvent.selection.start)); setCaretContent(getNextChars(value ?? '', webEvent.nativeEvent.selection.start)); }); const selectionValue = { diff --git a/src/components/Icon/__mocks__/Expensicons.ts b/src/components/Icon/__mocks__/Expensicons.ts index e268b109f0a5..78ad86210bf0 100644 --- a/src/components/Icon/__mocks__/Expensicons.ts +++ b/src/components/Icon/__mocks__/Expensicons.ts @@ -1,7 +1,4 @@ -// eslint-disable-next-line import/no-import-module-exports -import type {SvgProps} from 'react-native-svg'; - -const Expensicons = jest.requireActual>>('../Expensicons'); +const Expensicons = jest.requireActual('../Expensicons'); module.exports = Object.keys(Expensicons).reduce((prev, curr) => { // We set the name of the anonymous mock function here so we can dynamically build the list of mocks and access the diff --git a/src/components/OfflineWithFeedback.tsx b/src/components/OfflineWithFeedback.tsx index 1ff3ee2ed737..ba9ce9858d03 100644 --- a/src/components/OfflineWithFeedback.tsx +++ b/src/components/OfflineWithFeedback.tsx @@ -9,7 +9,6 @@ import * as ErrorUtils from '@libs/ErrorUtils'; import type {MaybePhraseKey} from '@libs/Localize'; import mapChildrenFlat from '@libs/mapChildrenFlat'; import shouldRenderOffscreen from '@libs/shouldRenderOffscreen'; -import type {AllStyles} from '@styles/utils/types'; import CONST from '@src/CONST'; import type * as OnyxCommon from '@src/types/onyx/OnyxCommon'; import type {ReceiptError, ReceiptErrors} from '@src/types/onyx/Transaction'; @@ -112,13 +111,12 @@ function OfflineWithFeedback({ return child; } - const childProps: {children: React.ReactNode | undefined; style: AllStyles} = child.props; const props: StrikethroughProps = { - style: StyleUtils.combineStyles(childProps.style, styles.offlineFeedback.deleted, styles.userSelectNone), + style: StyleUtils.combineStyles(child.props.style, styles.offlineFeedback.deleted, styles.userSelectNone), }; - if (childProps.children) { - props.children = applyStrikeThrough(childProps.children); + if (child.props.children) { + props.children = applyStrikeThrough(child.props.children); } return React.cloneElement(child, props); diff --git a/src/components/Onfido/BaseOnfidoWeb.tsx b/src/components/Onfido/BaseOnfidoWeb.tsx index 94124180bea3..fefe2ab0a6d1 100644 --- a/src/components/Onfido/BaseOnfidoWeb.tsx +++ b/src/components/Onfido/BaseOnfidoWeb.tsx @@ -1,5 +1,4 @@ import {Onfido as OnfidoSDK} from 'onfido-sdk-ui'; -import type {ErrorType} from 'onfido-sdk-ui/types/Types'; import React, {forwardRef, useEffect} from 'react'; import type {ForwardedRef} from 'react'; import type {LocaleContextProps} from '@components/LocaleContextProvider'; @@ -93,9 +92,9 @@ function initializeOnfido({sdkToken, onSuccess, onError, onUserExit, preferredLo } onSuccess(data); }, - onError: (error: ErrorType) => { + onError: (error) => { const errorType = error.type; - const errorMessage: string = error.message ?? CONST.ERROR.UNKNOWN_ERROR; + const errorMessage = error.message ?? CONST.ERROR.UNKNOWN_ERROR; Log.hmmm('Onfido error', {errorType, errorMessage}); if (errorType === CONST.WALLET.ERROR.ONFIDO_USER_CONSENT_DENIED) { onUserExit(); diff --git a/src/components/Onfido/index.native.tsx b/src/components/Onfido/index.native.tsx index 10badbcec414..a7e7a277fff9 100644 --- a/src/components/Onfido/index.native.tsx +++ b/src/components/Onfido/index.native.tsx @@ -1,5 +1,4 @@ import {OnfidoCaptureType, OnfidoCountryCode, OnfidoDocumentType, Onfido as OnfidoSDK, OnfidoTheme} from '@onfido/react-native-sdk'; -import type {ErrorType} from 'onfido-sdk-ui/types/Types'; import React, {useEffect} from 'react'; import {Alert, Linking} from 'react-native'; import {checkMultiple, PERMISSIONS, RESULTS} from 'react-native-permissions'; @@ -30,15 +29,15 @@ function Onfido({sdkToken, onUserExit, onSuccess, onError}: OnfidoProps) { }, }) .then(onSuccess) - .catch((error: ErrorType) => { - const errorMessage: string = error.message ?? CONST.ERROR.UNKNOWN_ERROR; + .catch((error) => { + const errorMessage = error.message ?? CONST.ERROR.UNKNOWN_ERROR; const errorType = error.type; Log.hmmm('Onfido error on native', {errorType, errorMessage}); // If the user cancels the Onfido flow we won't log this error as it's normal. In the React Native SDK the user exiting the flow will trigger this error which we can use as // our "user exited the flow" callback. On web, this event has it's own callback passed as a config so we don't need to bother with this there. - if (([CONST.ONFIDO.ERROR.USER_CANCELLED, CONST.ONFIDO.ERROR.USER_TAPPED_BACK, CONST.ONFIDO.ERROR.USER_EXITED] as string[]).includes(errorMessage)) { + if ([CONST.ONFIDO.ERROR.USER_CANCELLED, CONST.ONFIDO.ERROR.USER_TAPPED_BACK, CONST.ONFIDO.ERROR.USER_EXITED].includes(errorMessage)) { onUserExit(); return; } diff --git a/src/components/ProfilingToolMenu/BaseProfilingToolMenu.tsx b/src/components/ProfilingToolMenu/BaseProfilingToolMenu.tsx index 6ab1761fda62..ff34db881a35 100644 --- a/src/components/ProfilingToolMenu/BaseProfilingToolMenu.tsx +++ b/src/components/ProfilingToolMenu/BaseProfilingToolMenu.tsx @@ -115,7 +115,7 @@ function BaseProfilingToolMenu({isProfilingInProgress = false, pathToBeUsed, dis .then(() => { Log.hmmm('[ProfilingToolMenu] file copied successfully'); }) - .catch((error: Record) => { + .catch((error) => { Log.hmmm('[ProfilingToolMenu] error copying file: ', error); }); diff --git a/src/components/SignInButtons/AppleSignIn/index.android.tsx b/src/components/SignInButtons/AppleSignIn/index.android.tsx index ec669590d029..cfd1c48ee8b5 100644 --- a/src/components/SignInButtons/AppleSignIn/index.android.tsx +++ b/src/components/SignInButtons/AppleSignIn/index.android.tsx @@ -37,11 +37,11 @@ function AppleSignIn() { const handleSignIn = () => { appleSignInRequest() .then((token) => Session.beginAppleSignIn(token)) - .catch((error: Record) => { - if (error.message === appleAuthAndroid.Error.SIGNIN_CANCELLED) { + .catch((e) => { + if (e.message === appleAuthAndroid.Error.SIGNIN_CANCELLED) { return null; } - Log.alert('[Apple Sign In] Apple authentication failed', error); + Log.alert('[Apple Sign In] Apple authentication failed', e); }); }; return ( diff --git a/src/components/SignInButtons/AppleSignIn/index.ios.tsx b/src/components/SignInButtons/AppleSignIn/index.ios.tsx index 4df8375edad8..3fb1179d0365 100644 --- a/src/components/SignInButtons/AppleSignIn/index.ios.tsx +++ b/src/components/SignInButtons/AppleSignIn/index.ios.tsx @@ -1,5 +1,4 @@ import appleAuth from '@invertase/react-native-apple-authentication'; -import type {AppleError} from '@invertase/react-native-apple-authentication'; import React from 'react'; import IconButton from '@components/SignInButtons/IconButton'; import Log from '@libs/Log'; @@ -36,11 +35,11 @@ function AppleSignIn() { const handleSignIn = () => { appleSignInRequest() .then((token) => Session.beginAppleSignIn(token)) - .catch((error: {code: AppleError}) => { - if (error.code === appleAuth.Error.CANCELED) { + .catch((e) => { + if (e.code === appleAuth.Error.CANCELED) { return null; } - Log.alert('[Apple Sign In] Apple authentication failed', error); + Log.alert('[Apple Sign In] Apple authentication failed', e); }); }; return ( diff --git a/src/libs/EmojiUtils.ts b/src/libs/EmojiUtils.ts index 9d82cefe831c..c8b384a5a97c 100644 --- a/src/libs/EmojiUtils.ts +++ b/src/libs/EmojiUtils.ts @@ -10,8 +10,6 @@ import ONYXKEYS from '@src/ONYXKEYS'; import type {FrequentlyUsedEmoji, Locale} from '@src/types/onyx'; import type {ReportActionReaction, UsersReactions} from '@src/types/onyx/ReportActionReactions'; import type IconAsset from '@src/types/utils/IconAsset'; -import type EmojiTrie from './EmojiTrie'; -import type {SupportedLanguage} from './EmojiTrie'; type HeaderIndice = {code: string; index: number; icon: IconAsset}; type EmojiSpacer = {code: string; spacer: boolean}; @@ -314,9 +312,9 @@ function getAddedEmojis(currentEmojis: Emoji[], formerEmojis: Emoji[]): Emoji[] */ function replaceEmojis(text: string, preferredSkinTone: OnyxEntry = CONST.EMOJI_DEFAULT_SKIN_TONE, lang: Locale = CONST.LOCALES.DEFAULT): ReplacedEmoji { // emojisTrie is importing the emoji JSON file on the app starting and we want to avoid it - const emojisTrie: typeof EmojiTrie = require('./EmojiTrie').default; + const emojisTrie = require('./EmojiTrie').default; - const trie = emojisTrie[lang as SupportedLanguage]; + const trie = emojisTrie[lang]; if (!trie) { return {text, emojis: []}; } @@ -392,9 +390,9 @@ function replaceAndExtractEmojis(text: string, preferredSkinTone: OnyxEntry res.json()) .then((json) => { - const productionVersion: string | semver.SemVer = json.tag_name; + const productionVersion = json.tag_name; if (!productionVersion) { AppUpdate.setIsAppInBeta(false); resolve(false); diff --git a/src/libs/Localize/index.ts b/src/libs/Localize/index.ts index 06fc4fcfc199..39a874199004 100644 --- a/src/libs/Localize/index.ts +++ b/src/libs/Localize/index.ts @@ -67,7 +67,7 @@ type Phrase = TranslationFlatObject[TKey] extends */ const translationCache = new Map, Map>( Object.values(CONST.LOCALES).reduce((cache, locale) => { - cache.push([locale, new Map()]); + cache.push([locale, new Map()]); return cache; }, [] as Array<[ValueOf, Map]>), ); diff --git a/src/libs/Middleware/Logging.ts b/src/libs/Middleware/Logging.ts index f10e8d2f5120..19d767c8a4b1 100644 --- a/src/libs/Middleware/Logging.ts +++ b/src/libs/Middleware/Logging.ts @@ -1,5 +1,4 @@ import {SIDE_EFFECT_REQUEST_COMMANDS} from '@libs/API/types'; -import type HttpsError from '@libs/Errors/HttpsError'; import Log from '@libs/Log'; import CONST from '@src/CONST'; import type Request from '@src/types/onyx/Request'; @@ -43,7 +42,7 @@ const Logging: Middleware = (response, request) => { logRequestDetails(`Finished API request in ${Date.now() - startTime}ms`, request, data); return data; }) - .catch((error: HttpsError) => { + .catch((error) => { const logParams: Record = { message: error.message, status: error.status, @@ -71,12 +70,12 @@ const Logging: Middleware = (response, request) => { CONST.ERROR.IOS_NETWORK_CONNECTION_LOST_RUSSIAN, CONST.ERROR.IOS_NETWORK_CONNECTION_LOST_SWEDISH, CONST.ERROR.IOS_NETWORK_CONNECTION_LOST_SPANISH, - ].some((message) => message === error.message) + ].includes(error.message) ) { // These errors seem to happen for native devices with interrupted connections. Often we will see logs about Pusher disconnecting together with these. // This type of error may also indicate a problem with SSL certs. Log.hmmm('[Network] API request error: Connection interruption likely', logParams); - } else if ([CONST.ERROR.FIREFOX_DOCUMENT_LOAD_ABORTED, CONST.ERROR.SAFARI_DOCUMENT_LOAD_ABORTED].some((message) => message === error.message)) { + } else if ([CONST.ERROR.FIREFOX_DOCUMENT_LOAD_ABORTED, CONST.ERROR.SAFARI_DOCUMENT_LOAD_ABORTED].includes(error.message)) { // This message can be observed page load is interrupted (closed or navigated away). Log.hmmm('[Network] API request error: User likely navigated away from or closed browser', logParams); } else if (error.message === CONST.ERROR.IOS_LOAD_FAILED) { diff --git a/src/libs/Notification/LocalNotification/BrowserNotifications.ts b/src/libs/Notification/LocalNotification/BrowserNotifications.ts index 18fd8256a5ec..ee6d00ee2208 100644 --- a/src/libs/Notification/LocalNotification/BrowserNotifications.ts +++ b/src/libs/Notification/LocalNotification/BrowserNotifications.ts @@ -153,7 +153,7 @@ export default { */ clearNotifications(shouldClearNotification: (notificationData: LocalNotificationData) => boolean) { Object.values(notificationCache) - .filter((notification) => shouldClearNotification(notification.data as LocalNotificationData)) + .filter((notification) => shouldClearNotification(notification.data)) .forEach((notification) => notification.close()); }, }; diff --git a/src/libs/Notification/PushNotification/index.native.ts b/src/libs/Notification/PushNotification/index.native.ts index 34699f0610e1..426f03c6d408 100644 --- a/src/libs/Notification/PushNotification/index.native.ts +++ b/src/libs/Notification/PushNotification/index.native.ts @@ -130,7 +130,7 @@ const register: Register = (notificationID) => { // Refresh notification opt-in status NVP for the new user. refreshNotificationOptInStatus(); }) - .catch((error: Record) => { + .catch((error) => { Log.warn('[PushNotification] Failed to register for push notifications! Reason: ', error); }); }; diff --git a/src/libs/Pusher/pusher.ts b/src/libs/Pusher/pusher.ts index 2c5dda801359..f67775bd05ed 100644 --- a/src/libs/Pusher/pusher.ts +++ b/src/libs/Pusher/pusher.ts @@ -36,9 +36,7 @@ type PusherEventMap = { [TYPE.USER_IS_LEAVING_ROOM]: UserIsLeavingRoomEvent; }; -type EventData = {chunk?: string; id?: string; index?: number; final?: boolean} & (EventName extends keyof PusherEventMap - ? PusherEventMap[EventName] - : OnyxUpdatesFromServer); +type EventData = EventName extends keyof PusherEventMap ? PusherEventMap[EventName] : OnyxUpdatesFromServer; type EventCallbackError = {type: ValueOf; data: {code: number}}; @@ -168,7 +166,7 @@ function bindEventToChannel(channel: Channel return; } - let data: EventData; + let data; try { data = isObject(eventData) ? eventData : JSON.parse(eventData as string); } catch (err) { @@ -191,9 +189,7 @@ function bindEventToChannel(channel: Channel // Add it to the rolling list. const chunkedEvent = chunkedDataEvents[data.id]; - if (data.index !== undefined) { - chunkedEvent.chunks[data.index] = data.chunk; - } + chunkedEvent.chunks[data.index] = data.chunk; // If this is the last packet, mark that we've hit the end. if (data.final) { @@ -204,7 +200,7 @@ function bindEventToChannel(channel: Channel // packet. if (chunkedEvent.receivedFinal && chunkedEvent.chunks.length === Object.keys(chunkedEvent.chunks).length) { try { - eventCallback(JSON.parse(chunkedEvent.chunks.join('')) as EventData); + eventCallback(JSON.parse(chunkedEvent.chunks.join(''))); } catch (err) { Log.alert('[Pusher] Unable to parse chunked JSON response from Pusher', { error: err, diff --git a/src/libs/actions/Device/index.ts b/src/libs/actions/Device/index.ts index ed700c06a97f..e7c19d20e4fe 100644 --- a/src/libs/actions/Device/index.ts +++ b/src/libs/actions/Device/index.ts @@ -43,7 +43,7 @@ function setDeviceID() { Log.info('Got new deviceID', false, uniqueID); Onyx.set(ONYXKEYS.DEVICE_ID, uniqueID); }) - .catch((error: Error) => Log.info('Found existing deviceID', false, error.message)); + .catch((err) => Log.info('Found existing deviceID', false, err.message)); } /** diff --git a/src/pages/home/report/ContextMenu/ContextMenuActions.tsx b/src/pages/home/report/ContextMenu/ContextMenuActions.tsx index afb3d69d3330..aeeb27789d76 100644 --- a/src/pages/home/report/ContextMenu/ContextMenuActions.tsx +++ b/src/pages/home/report/ContextMenu/ContextMenuActions.tsx @@ -368,7 +368,7 @@ const ContextMenuActions: ContextMenuAction[] = [ Clipboard.setString(Localize.translateLocal('iou.unheldExpense')); } else if (content) { setClipboardMessage( - content.replace(/()(.*?)(<\/mention-user>)/gi, (match, openTag: string, innerContent: string, closeTag: string): string => { + content.replace(/()(.*?)(<\/mention-user>)/gi, (match, openTag, innerContent, closeTag): string => { const modifiedContent = Str.removeSMSDomain(innerContent) || ''; return openTag + modifiedContent + closeTag || ''; }), diff --git a/src/pages/home/report/ReportActionCompose/ComposerWithSuggestions/ComposerWithSuggestions.tsx b/src/pages/home/report/ReportActionCompose/ComposerWithSuggestions/ComposerWithSuggestions.tsx index 8112bdc6dae0..7c7ab9a01307 100644 --- a/src/pages/home/report/ReportActionCompose/ComposerWithSuggestions/ComposerWithSuggestions.tsx +++ b/src/pages/home/report/ReportActionCompose/ComposerWithSuggestions/ComposerWithSuggestions.tsx @@ -177,11 +177,6 @@ type ComposerWithSuggestionsProps = ComposerWithSuggestionsOnyxProps & policyID: string; }; -type SwitchToCurrentReportProps = { - preexistingReportID: string; - callback: () => void; -}; - const {RNTextInputReset} = NativeModules; const isIOSNative = getPlatform() === CONST.PLATFORM.IOS; @@ -341,7 +336,7 @@ function ComposerWithSuggestions( const debouncedSaveReportComment = useMemo( () => - lodashDebounce((selectedReportID: string, newComment: string | null) => { + lodashDebounce((selectedReportID, newComment) => { Report.saveReportDraftComment(selectedReportID, newComment); isCommentPendingSaved.current = false; }, 1000), @@ -349,7 +344,7 @@ function ComposerWithSuggestions( ); useEffect(() => { - const switchToCurrentReport = DeviceEventEmitter.addListener(`switchToPreExistingReport_${reportID}`, ({preexistingReportID, callback}: SwitchToCurrentReportProps) => { + const switchToCurrentReport = DeviceEventEmitter.addListener(`switchToPreExistingReport_${reportID}`, ({preexistingReportID, callback}) => { if (!commentRef.current) { callback(); return; diff --git a/src/pages/home/report/ReportActionsList.tsx b/src/pages/home/report/ReportActionsList.tsx index bdc0b80375fa..d8aed24e3b13 100644 --- a/src/pages/home/report/ReportActionsList.tsx +++ b/src/pages/home/report/ReportActionsList.tsx @@ -303,12 +303,12 @@ function ReportActionsList({ setCurrentUnreadMarker(null); }; - const unreadActionSubscription = DeviceEventEmitter.addListener(`unreadAction_${report.reportID}`, (newLastReadTime: string) => { + const unreadActionSubscription = DeviceEventEmitter.addListener(`unreadAction_${report.reportID}`, (newLastReadTime) => { resetUnreadMarker(newLastReadTime); setMessageManuallyMarkedUnread(new Date().getTime()); }); - const readNewestActionSubscription = DeviceEventEmitter.addListener(`readNewestAction_${report.reportID}`, (newLastReadTime: string) => { + const readNewestActionSubscription = DeviceEventEmitter.addListener(`readNewestAction_${report.reportID}`, (newLastReadTime) => { resetUnreadMarker(newLastReadTime); setMessageManuallyMarkedUnread(0); }); diff --git a/src/pages/iou/request/step/IOURequestStepScan/index.native.tsx b/src/pages/iou/request/step/IOURequestStepScan/index.native.tsx index b844aa29f670..c022a079df65 100644 --- a/src/pages/iou/request/step/IOURequestStepScan/index.native.tsx +++ b/src/pages/iou/request/step/IOURequestStepScan/index.native.tsx @@ -105,11 +105,11 @@ function IOURequestStepScan({ return; } - camera.current.focus(point).catch((error: Record) => { - if (error.message === '[unknown/unknown] Cancelled by another startFocusAndMetering()') { + camera.current.focus(point).catch((ex) => { + if (ex.message === '[unknown/unknown] Cancelled by another startFocusAndMetering()') { return; } - Log.warn('Error focusing camera', error); + Log.warn('Error focusing camera', ex); }); }; diff --git a/tests/e2e/server/index.ts b/tests/e2e/server/index.ts index 52e50fefc0ae..51b73447bab4 100644 --- a/tests/e2e/server/index.ts +++ b/tests/e2e/server/index.ts @@ -153,7 +153,7 @@ const createServerInstance = (): ServerInstance => { res.statusCode = 500; res.end('Error executing command'); }) - .catch((error: string) => { + .catch((error) => { Logger.error('Error executing command', error); res.statusCode = 500; res.end('Error executing command'); diff --git a/tests/ui/UnreadIndicatorsTest.tsx b/tests/ui/UnreadIndicatorsTest.tsx index 0f13062b2e94..e5c7e0359eed 100644 --- a/tests/ui/UnreadIndicatorsTest.tsx +++ b/tests/ui/UnreadIndicatorsTest.tsx @@ -5,7 +5,6 @@ import {addSeconds, format, subMinutes, subSeconds} from 'date-fns'; import {utcToZonedTime} from 'date-fns-tz'; import React from 'react'; import {AppState, DeviceEventEmitter, Linking} from 'react-native'; -import type {ViewStyle} from 'react-native'; import type {OnyxEntry} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; import type Animated from 'react-native-reanimated'; @@ -78,7 +77,7 @@ const createAddListenerMock = (): ListenerMock => { transitionEndListeners.forEach((transitionEndListener) => transitionEndListener()); }; - const addListener: jest.Mock = jest.fn().mockImplementation((listener, callback: () => void) => { + const addListener: jest.Mock = jest.fn().mockImplementation((listener, callback) => { if (listener === 'transitionEnd') { transitionEndListeners.push(callback); } @@ -158,10 +157,7 @@ function scrollUpToRevealNewMessagesBadge() { function isNewMessagesBadgeVisible(): boolean { const hintText = Localize.translateLocal('accessibilityHints.scrollToNewestMessages'); const badge = screen.queryByAccessibilityHint(hintText); - const badgeProps = badge?.props as {style: ViewStyle}; - const transformStyle = badgeProps.style.transform?.[0] as {translateY: number}; - - return Math.round(transformStyle.translateY) === -40; + return Math.round(badge?.props.style.transform[0].translateY) === -40; } function navigateToSidebar(): Promise { diff --git a/tests/unit/MiddlewareTest.ts b/tests/unit/MiddlewareTest.ts index 6954b22b2706..cc4bf7d0df6b 100644 --- a/tests/unit/MiddlewareTest.ts +++ b/tests/unit/MiddlewareTest.ts @@ -49,9 +49,9 @@ describe('Middleware', () => { expect(global.fetch).toHaveBeenCalledTimes(2); expect(global.fetch).toHaveBeenLastCalledWith('https://www.expensify.com.dev/api/AddComment?', expect.anything()); - TestHelper.assertFormDataMatchesObject((global.fetch as jest.Mock).mock.calls[1][1].body as TestHelper.FormData, {reportID: '1234', reportActionID: '5678'}); + TestHelper.assertFormDataMatchesObject((global.fetch as jest.Mock).mock.calls[1][1].body, {reportID: '1234', reportActionID: '5678'}); expect(global.fetch).toHaveBeenNthCalledWith(1, 'https://www.expensify.com.dev/api/OpenReport?', expect.anything()); - TestHelper.assertFormDataMatchesObject((global.fetch as jest.Mock).mock.calls[0][1].body as TestHelper.FormData, {reportID: '1234'}); + TestHelper.assertFormDataMatchesObject((global.fetch as jest.Mock).mock.calls[0][1].body, {reportID: '1234'}); }); test('Request with preexistingReportID', async () => { @@ -93,9 +93,9 @@ describe('Middleware', () => { expect(global.fetch).toHaveBeenCalledTimes(2); expect(global.fetch).toHaveBeenLastCalledWith('https://www.expensify.com.dev/api/AddComment?', expect.anything()); - TestHelper.assertFormDataMatchesObject((global.fetch as jest.Mock).mock.calls[1][1].body as TestHelper.FormData, {reportID: '5555', reportActionID: '5678'}); + TestHelper.assertFormDataMatchesObject((global.fetch as jest.Mock).mock.calls[1][1].body, {reportID: '5555', reportActionID: '5678'}); expect(global.fetch).toHaveBeenNthCalledWith(1, 'https://www.expensify.com.dev/api/OpenReport?', expect.anything()); - TestHelper.assertFormDataMatchesObject((global.fetch as jest.Mock).mock.calls[0][1].body as TestHelper.FormData, {reportID: '1234'}); + TestHelper.assertFormDataMatchesObject((global.fetch as jest.Mock).mock.calls[0][1].body, {reportID: '1234'}); }); }); }); diff --git a/tests/unit/markPullRequestsAsDeployedTest.ts b/tests/unit/markPullRequestsAsDeployedTest.ts index 24a6733d1244..d533435273d4 100644 --- a/tests/unit/markPullRequestsAsDeployedTest.ts +++ b/tests/unit/markPullRequestsAsDeployedTest.ts @@ -196,7 +196,7 @@ platform | result }); it('comments on pull requests correctly for a standard production deploy', async () => { - mockGetInput.mockImplementation((key: string) => { + mockGetInput.mockImplementation((key) => { if (key === 'IS_PRODUCTION_DEPLOY') { return true; } @@ -226,7 +226,7 @@ platform | result }); it('comments on pull requests correctly for a cherry pick', async () => { - mockGetInput.mockImplementation((key: string) => { + mockGetInput.mockImplementation((key) => { if (key === 'PR_LIST') { return JSON.stringify([3]); } @@ -281,7 +281,7 @@ platform | result }); it('comments on pull requests correctly when one platform fails', async () => { - mockGetInput.mockImplementation((key: string) => { + mockGetInput.mockImplementation((key) => { if (key === 'ANDROID') { return 'skipped'; } diff --git a/tests/utils/TestHelper.ts b/tests/utils/TestHelper.ts index 11befebea340..bd107ba6ed56 100644 --- a/tests/utils/TestHelper.ts +++ b/tests/utils/TestHelper.ts @@ -230,7 +230,7 @@ const createAddListenerMock = () => { transitionEndListeners.forEach((transitionEndListener) => transitionEndListener()); }; - const addListener = jest.fn().mockImplementation((listener, callback: Listener) => { + const addListener = jest.fn().mockImplementation((listener, callback) => { if (listener === 'transitionEnd') { transitionEndListeners.push(callback); } @@ -242,5 +242,5 @@ const createAddListenerMock = () => { return {triggerTransitionEnd, addListener}; }; -export type {MockFetch, FormData}; +export type {MockFetch}; export {assertFormDataMatchesObject, buildPersonalDetails, buildTestReportComment, createAddListenerMock, getGlobalFetchMock, setPersonalDetails, signInWithTestUser, signOutTestUser}; diff --git a/tests/utils/collections/reportActions.ts b/tests/utils/collections/reportActions.ts index 152358cedb49..65cbb3ba966e 100644 --- a/tests/utils/collections/reportActions.ts +++ b/tests/utils/collections/reportActions.ts @@ -2,16 +2,17 @@ import {rand, randAggregation, randBoolean, randWord} from '@ngneat/falso'; import {format} from 'date-fns'; import CONST from '@src/CONST'; import type {ReportAction} from '@src/types/onyx'; -import type {ActionName} from '@src/types/onyx/OriginalMessage'; -import type DeepRecord from '@src/types/utils/DeepRecord'; -const flattenActionNamesValues = (actionNames: DeepRecord) => { - let result: ActionName[] = []; - Object.values(actionNames).forEach((value) => { - if (typeof value === 'object') { - result = result.concat(flattenActionNamesValues(value)); +type ActionType = keyof typeof CONST.REPORT.ACTIONS.TYPE; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const flattenActionNamesValues = (actionNames: any) => { + let result = [] as ActionType[]; + Object.keys(actionNames).forEach((key) => { + if (typeof actionNames[key] === 'object') { + result = result.concat(flattenActionNamesValues(actionNames[key])); } else { - result.push(value); + result.push(actionNames[key]); } }); return result; diff --git a/workflow_tests/utils/ExtendedAct.ts b/workflow_tests/utils/ExtendedAct.ts index e2bb12ec8e01..b0f4d7e159e4 100644 --- a/workflow_tests/utils/ExtendedAct.ts +++ b/workflow_tests/utils/ExtendedAct.ts @@ -42,14 +42,14 @@ class ExtendedAct extends Act { if (opts.workflowFile) { workflowFiles = [path.basename(opts.workflowFile)]; } else if (this['workflowFile'] !== this['cwd']) { - workflowFiles = [path.basename(this['workflowFile'] as string)]; + workflowFiles = [path.basename(this['workflowFile'])]; } else { const availableWorkflows = await this.list(undefined, opts.cwd, opts.workflowFile); workflowFiles = availableWorkflows.filter(filter).map((workflow: Workflow) => workflow.workflowFile); } return workflowFiles.map((workflowFile) => { - const jobMocker = new JobMocker(workflowFile, opts.cwd ?? (this['cwd'] as string)); + const jobMocker = new JobMocker(workflowFile, opts.cwd ?? this['cwd']); return jobMocker.mock(opts.mockJobs); }); } diff --git a/workflow_tests/utils/preGenerateTest.ts b/workflow_tests/utils/preGenerateTest.ts index 1e7e7bb04184..25bdb8f00ae3 100644 --- a/workflow_tests/utils/preGenerateTest.ts +++ b/workflow_tests/utils/preGenerateTest.ts @@ -7,8 +7,6 @@ import {exit} from 'process'; import yaml from 'yaml'; import type {YamlMockJob, YamlWorkflow} from './JobMocker'; -type Step = {name: string; with?: string; envs?: string[]; inputs?: string[]}; - const workflowsDirectory = path.resolve(__dirname, '..', '..', '.github', 'workflows'); const workflowTestsDirectory = path.resolve(__dirname, '..'); const workflowTestMocksDirectory = path.join(workflowTestsDirectory, 'mocks'); @@ -201,7 +199,7 @@ const parseWorkflowFile = (workflow: YamlWorkflow) => { workflowJobs[jobId] = { steps: [], }; - job.steps.forEach((step: Step) => { + job.steps.forEach((step) => { const workflowStep = { name: step.name, inputs: Object.keys(step.with ?? {}), @@ -245,7 +243,7 @@ const getAssertionsFileContent = (jobs: Record): string => Object.entries(jobs).forEach(([jobId, job]) => { let stepAssertionsContent = ''; - job.steps.forEach((step: Step) => { + job.steps.forEach((step) => { stepAssertionsContent += stepAssertionTemplate(step.name, jobId.toUpperCase(), step.name, step.inputs, step.envs); }); const jobAssertionName = `assert${jobId.charAt(0).toUpperCase() + jobId.slice(1)}JobExecuted`; @@ -277,7 +275,7 @@ checkIfMocksFileExists(workflowTestMocksDirectory, workflowTestMocksFileName); const workflowTestAssertionsFileName = `${workflowName}Assertions.ts`; checkIfAssertionsFileExists(workflowTestAssertionsDirectory, workflowTestAssertionsFileName); -const workflow: YamlWorkflow = yaml.parse(fs.readFileSync(workflowFilePath, 'utf8')); +const workflow = yaml.parse(fs.readFileSync(workflowFilePath, 'utf8')); const workflowJobs = parseWorkflowFile(workflow); const mockFileContent = getMockFileContent(workflowName, workflowJobs);