From 900ae094d85b11c67d53dd14af50a2bda5db4495 Mon Sep 17 00:00:00 2001 From: Sam Zhou Date: Fri, 5 Jun 2026 19:17:18 -0400 Subject: [PATCH] [flow] Bump flow to v0.317.0 (#36701) ## Summary Mostly changing the casting syntax from `(x: Y)` to `x as Y`, as the old syntax was deprecated and always causing an error in Flow ## How did you test this change? `yarn flow-ci` --- package.json | 4 +- packages/react-cache/src/LRU.js | 16 +- packages/react-cache/src/ReactCacheOld.js | 10 +- .../react-client/src/ReactFlightClient.js | 204 +++++----- .../src/ReactFlightReplyClient.js | 43 +- .../src/ReactFlightTemporaryReferences.js | 2 +- .../react-debug-tools/src/ReactDebugHooks.js | 60 ++- packages/react-devtools-core/src/backend.js | 54 ++- .../react-devtools-core/src/standalone.js | 8 +- .../src/main/index.js | 30 +- packages/react-devtools-inline/src/backend.js | 2 +- .../react-devtools-inline/src/frontend.js | 4 +- .../setupNativeStyleEditor.js | 72 ++-- .../src/backend/StyleX/utils.js | 8 +- .../src/backend/agent.js | 70 ++-- .../fiber/DevToolsFiberComponentStack.js | 4 +- .../src/backend/fiber/renderer.js | 117 +++--- .../fiber/shared/DevToolsFiberInspection.js | 4 +- .../DevToolsFiberInternalReactConstants.js | 2 +- .../src/backend/legacy/renderer.js | 6 +- .../src/backend/profilingHooks.js | 8 +- .../src/backend/shared/ReactSymbols.js | 4 +- .../src/backend/utils/index.js | 4 +- .../src/backend/utils/parseStackTrace.js | 4 +- .../backend/views/Highlighter/Highlighter.js | 2 +- .../src/backend/views/Highlighter/Overlay.js | 4 +- .../src/backend/views/Highlighter/index.js | 6 +- .../src/backend/views/TraceUpdates/canvas.js | 2 +- .../src/backend/views/TraceUpdates/index.js | 2 +- .../react-devtools-shared/src/backendAPI.js | 2 +- packages/react-devtools-shared/src/bridge.js | 2 +- .../config/DevToolsFeatureFlags.core-fb.js | 2 +- .../config/DevToolsFeatureFlags.core-oss.js | 2 +- .../DevToolsFeatureFlags.extension-fb.js | 2 +- .../DevToolsFeatureFlags.extension-oss.js | 2 +- .../src/devtools/ContextMenu/ContextMenu.js | 4 +- .../src/devtools/cache.js | 16 +- .../src/devtools/store.js | 12 +- .../src/devtools/utils.js | 2 +- .../devtools/views/Components/Components.js | 2 +- .../Components/InspectedElementContext.js | 2 +- .../Components/InspectedElementContextTree.js | 2 +- .../Components/InspectedElementHooksTree.js | 6 +- .../Components/InspectedElementStateTree.js | 2 +- .../Components/NativeStyleEditor/context.js | 2 +- .../views/Components/OwnersListContext.js | 8 +- .../src/devtools/views/Components/Tree.js | 2 +- .../devtools/views/Components/TreeContext.js | 53 +-- .../Components/ViewElementSourceContext.js | 2 +- .../src/devtools/views/DevTools.js | 6 +- .../src/devtools/views/Editor/EditorPane.js | 2 +- .../src/devtools/views/ErrorBoundary/cache.js | 12 +- .../InspectedElement/InspectedElementPane.js | 2 +- .../src/devtools/views/ModalDialog.js | 2 +- .../views/Profiler/CommitFlamegraph.js | 8 +- .../Profiler/CommitFlamegraphListItem.js | 4 +- .../devtools/views/Profiler/CommitRanked.js | 8 +- .../views/Profiler/CommitRankedListItem.js | 4 +- .../views/Profiler/CommitTreeBuilder.js | 50 +-- .../views/Profiler/FlamegraphChartBuilder.js | 2 +- .../views/Profiler/HoveredFiberInfo.js | 2 +- .../src/devtools/views/Profiler/Profiler.js | 2 +- .../views/Profiler/ProfilerContext.js | 6 +- .../Profiler/ProfilingImportExportButtons.js | 4 +- .../views/Profiler/RankedChartBuilder.js | 2 +- .../Profiler/SidebarSelectedFiberInfo.js | 4 +- .../views/Profiler/SnapshotCommitList.js | 6 +- .../views/Profiler/SnapshotCommitListItem.js | 4 +- .../views/Profiler/SnapshotSelector.js | 2 +- .../devtools/views/Profiler/WhatChanged.js | 2 +- .../useCommitFilteringAndNavigation.js | 2 +- .../views/Settings/ComponentsSettings.js | 14 +- .../views/Settings/SettingsContext.js | 20 +- .../views/Settings/SettingsModalContext.js | 2 +- .../views/SuspenseTab/SuspenseRects.js | 2 +- .../devtools/views/SuspenseTab/SuspenseTab.js | 2 +- .../views/SuspenseTab/SuspenseTreeContext.js | 4 +- .../src/devtools/views/TabBar.js | 2 +- .../src/devtools/views/context.js | 4 +- .../src/devtools/views/hooks.js | 4 +- .../src/devtools/views/utils.js | 2 +- .../src/dynamicImportCache.js | 8 +- packages/react-devtools-shared/src/hook.js | 24 +- .../src/hookNamesCache.js | 12 +- .../src/hooks/SourceMapConsumer.js | 16 +- .../parseHookNames/loadSourceAndMetadata.js | 14 +- .../parseHookNames/parseSourceAndMetadata.js | 8 +- .../react-devtools-shared/src/hydration.js | 18 +- .../src/inspectedElementCache.js | 10 +- .../src/inspectedElementMutableSource.js | 6 +- packages/react-devtools-shared/src/utils.js | 34 +- .../src/app/DeeplyNestedComponents/index.js | 2 +- .../app/InspectableElements/CustomHooks.js | 4 +- .../src/app/ToDoList/ListItem.js | 2 +- .../react-devtools-shell/src/app/devtools.js | 10 +- .../react-devtools-shell/src/app/index.js | 2 +- .../src/e2e-apps/ListApp.js | 2 +- .../src/e2e-regression/app-legacy.js | 2 +- .../src/e2e-regression/app.js | 2 +- packages/react-devtools-shell/src/e2e/app.js | 2 +- .../src/perf-regression/app.js | 2 +- .../src/EventTooltip.js | 4 +- .../react-devtools-timeline/src/Timeline.js | 2 +- .../src/TimelineContext.js | 2 +- .../src/TimelineSearchContext.js | 2 +- .../content-views/ComponentMeasuresView.js | 4 +- .../src/content-views/SuspenseEventsView.js | 2 +- .../src/content-views/utils/text.js | 2 +- .../src/createDataResourceFromImportedFile.js | 4 +- .../src/import-worker/preprocessData.js | 16 +- .../src/timelineCache.js | 12 +- .../src/utils/getBatchRange.js | 2 +- .../src/view-base/VerticalScrollView.js | 4 +- .../src/view-base/resizable/ResizableView.js | 4 +- .../src/client/DOMAccessibilityRoles.js | 4 +- .../src/client/DOMPropertyOperations.js | 20 +- .../src/client/ReactDOMComponent.js | 79 ++-- .../src/client/ReactDOMComponentTree.js | 92 ++--- .../src/client/ReactDOMContainer.js | 2 +- .../src/client/ReactDOMEventHandle.js | 14 +- .../src/client/ReactDOMInput.js | 22 +- .../src/client/ReactDOMSelect.js | 12 +- .../src/client/ReactDOMSrcObject.js | 2 +- .../src/client/ReactDOMTextarea.js | 12 +- .../src/client/ReactFiberConfigDOM.js | 383 +++++++++--------- .../src/client/ToStringValue.js | 2 +- .../src/client/inputValueTracking.js | 9 +- .../src/client/validateDOMNesting.js | 2 +- .../src/events/DOMEventProperties.js | 4 +- .../src/events/DOMPluginEventSystem.js | 20 +- .../src/events/EventRegistry.js | 2 +- .../src/events/ReactDOMEventReplaying.js | 24 +- .../src/events/forks/EventListener-www.js | 2 +- .../src/events/isEventSupported.js | 2 +- .../src/events/isTextInputElement.js | 2 +- .../src/events/plugins/ChangeEventPlugin.js | 16 +- .../events/plugins/EnterLeaveEventPlugin.js | 12 +- .../events/plugins/FormActionEventPlugin.js | 21 +- .../src/events/plugins/SelectEventPlugin.js | 2 +- .../src/events/plugins/SimpleEventPlugin.js | 4 +- .../ReactDOMFlightServerHostDispatcher.js | 4 +- .../server/ReactDOMServerExternalRuntime.js | 8 +- .../src/server/ReactFizzConfigDOM.js | 160 ++++---- .../src/server/escapeTextForBrowser.js | 2 +- .../src/shared/ReactDOMFormActions.js | 2 +- .../src/shared/sanitizeURL.js | 2 +- packages/react-dom/src/ReactDOMFB.js | 2 +- .../react-dom/src/ReactDOMSharedInternals.js | 2 +- .../src/ReactDOMSharedInternalsFB.js | 2 +- packages/react-dom/src/client/ReactDOMRoot.js | 6 +- .../react-dom/src/client/ReactDOMRootFB.js | 12 +- .../src/server/ReactDOMFizzServerBrowser.js | 16 +- .../src/server/ReactDOMFizzServerBun.js | 8 +- .../src/server/ReactDOMFizzServerEdge.js | 16 +- .../src/server/ReactDOMFizzServerNode.js | 20 +- .../src/server/ReactDOMFizzStaticBrowser.js | 8 +- .../src/server/ReactDOMFizzStaticEdge.js | 8 +- .../src/server/ReactDOMFizzStaticNode.js | 24 +- .../react-dom/src/test-utils/FizzTestUtils.js | 4 +- .../src/ReactFlightFBReferences.js | 4 +- .../src/ReactServerStreamConfigFB.js | 31 +- .../ReactFlightClientConfigBundlerFB.js | 16 +- .../src/client/ReactFlightDOMClientBrowser.js | 10 +- .../src/server/ReactFlightDOMServerNode.js | 18 +- .../react-markup/src/ReactMarkupClient.js | 4 +- .../react-markup/src/ReactMarkupServer.js | 8 +- packages/react-native-renderer/fabric.js | 2 +- .../src/ReactFabricComponentTree.js | 2 +- .../src/ReactFabricEventEmitter.js | 10 +- .../src/ReactFiberConfigFabric.js | 22 +- ...eactFiberConfigFabricWithViewTransition.js | 4 +- .../src/ReactNativeBridgeEventPlugin.js | 2 +- .../src/ReactNativeFiberInspector.js | 2 +- .../src/legacy-events/EventPluginRegistry.js | 2 +- .../ResponderTouchHistoryStore.js | 2 +- .../src/ReactNoopFlightServer.js | 4 +- .../src/ReactNoopServer.js | 2 +- .../src/createReactNoop.js | 28 +- .../react-reconciler/src/ReactChildFiber.js | 54 +-- .../src/ReactFiberApplyGesture.js | 6 +- .../src/ReactFiberAsyncAction.js | 8 +- .../src/ReactFiberAsyncDispatcher.js | 6 +- .../src/ReactFiberBeginWork.js | 78 ++-- .../src/ReactFiberCacheComponent.js | 8 +- .../src/ReactFiberCallUserSpace.js | 36 +- .../src/ReactFiberClassComponent.js | 6 +- .../src/ReactFiberClassUpdateQueue.js | 20 +- .../src/ReactFiberCommitEffects.js | 18 +- .../src/ReactFiberCommitWork.js | 100 ++--- .../src/ReactFiberCompleteWork.js | 36 +- .../src/ReactFiberComponentStack.js | 4 +- .../src/ReactFiberConcurrentUpdates.js | 14 +- .../src/ReactFiberDuplicateViewTransitions.js | 8 +- .../src/ReactFiberErrorLogger.js | 4 +- .../react-reconciler/src/ReactFiberHooks.js | 153 ++++--- .../src/ReactFiberHostContext.js | 2 +- .../src/ReactFiberHotReloading.js | 2 +- .../src/ReactFiberHydrationContext.js | 6 +- .../src/ReactFiberHydrationDiffs.js | 8 +- .../src/ReactFiberLegacyContext.js | 2 +- .../src/ReactFiberNewContext.js | 2 +- .../src/ReactFiberPerformanceTrack.js | 8 +- .../src/ReactFiberReconciler.js | 10 +- .../react-reconciler/src/ReactFiberRoot.js | 4 +- .../react-reconciler/src/ReactFiberScope.js | 2 +- .../src/ReactFiberThenable.js | 20 +- .../react-reconciler/src/ReactFiberThrow.js | 12 +- .../src/ReactFiberTransition.js | 6 +- .../src/ReactFiberTreeReflection.js | 2 +- .../src/ReactFiberViewTransitionComponent.js | 2 +- .../src/ReactFiberWorkLoop.js | 60 +-- .../src/ReactProfilerTimer.js | 4 +- .../src/ReactStrictModeWarnings.js | 2 +- .../src/ReactTestSelectors.js | 36 +- .../src/getComponentNameFromFiber.js | 10 +- .../react-refresh/src/ReactFreshRuntime.js | 4 +- .../src/ReactFlightESMReferences.js | 4 +- .../ReactFlightClientConfigBundlerESM.js | 12 +- .../src/client/ReactFlightDOMClientBrowser.js | 10 +- .../src/server/ReactFlightDOMServerNode.js | 26 +- .../src/ReactDOMServerFB.js | 2 +- .../src/ReactFlightParcelReferences.js | 4 +- .../ReactFlightClientConfigBundlerParcel.js | 2 +- .../src/client/ReactFlightDOMClientBrowser.js | 10 +- .../src/client/ReactFlightDOMClientEdge.js | 10 +- .../src/server/ReactFlightDOMServerBrowser.js | 10 +- .../src/server/ReactFlightDOMServerEdge.js | 12 +- .../src/server/ReactFlightDOMServerNode.js | 42 +- .../src/ReactFlightTurbopackReferences.js | 26 +- ...ReactFlightClientConfigBundlerTurbopack.js | 6 +- ...ightClientConfigBundlerTurbopackBrowser.js | 8 +- .../src/client/ReactFlightDOMClientBrowser.js | 10 +- .../src/client/ReactFlightDOMClientEdge.js | 10 +- .../src/server/ReactFlightDOMServerBrowser.js | 10 +- .../src/server/ReactFlightDOMServerEdge.js | 12 +- .../src/server/ReactFlightDOMServerNode.js | 42 +- .../src/ReactFlightUnbundledNodeRegister.js | 8 +- .../src/ReactFlightUnbundledReferences.js | 22 +- .../ReactFlightClientConfigBundlerNode.js | 8 +- .../src/client/ReactFlightDOMClientEdge.js | 10 +- .../src/server/ReactFlightDOMServerNode.js | 42 +- .../src/ReactFlightWebpackNodeRegister.js | 8 +- .../src/ReactFlightWebpackPlugin.js | 2 +- .../src/ReactFlightWebpackReferences.js | 26 +- .../ReactFlightClientConfigBundlerWebpack.js | 6 +- ...FlightClientConfigBundlerWebpackBrowser.js | 8 +- .../src/client/ReactFlightDOMClientBrowser.js | 10 +- .../src/client/ReactFlightDOMClientEdge.js | 10 +- .../src/server/ReactFlightDOMServerBrowser.js | 10 +- .../src/server/ReactFlightDOMServerEdge.js | 12 +- .../src/server/ReactFlightDOMServerNode.js | 42 +- .../src/ReactFizzAsyncDispatcher.js | 4 +- .../src/ReactFizzCallUserSpace.js | 12 +- .../src/ReactFizzClassComponent.js | 2 +- .../src/ReactFizzComponentStack.js | 8 +- packages/react-server/src/ReactFizzHooks.js | 28 +- .../src/ReactFizzLegacyContext.js | 2 +- packages/react-server/src/ReactFizzServer.js | 115 +++--- .../react-server/src/ReactFizzThenable.js | 18 +- .../src/ReactFlightActionServer.js | 4 +- .../src/ReactFlightCallUserSpace.js | 12 +- packages/react-server/src/ReactFlightHooks.js | 38 +- .../src/ReactFlightReplyServer.js | 88 ++-- .../react-server/src/ReactFlightServer.js | 217 +++++----- .../src/ReactFlightServerConfigDebugNode.js | 34 +- .../ReactFlightServerTemporaryReferences.js | 4 +- .../src/ReactFlightStackConfigV8.js | 6 +- .../react-server/src/ReactFlightThenable.js | 14 +- .../src/ReactServerStreamConfigBrowser.js | 9 +- .../src/ReactServerStreamConfigEdge.js | 9 +- .../src/ReactServerStreamConfigFB.js | 2 +- .../src/ReactServerStreamConfigNode.js | 29 +- .../src/flight/ReactFlightAsyncDispatcher.js | 6 +- .../src/forks/ReactFizzConfig.custom.js | 2 +- .../src/forks/ReactFizzConfig.dom-edge.js | 2 +- .../src/forks/ReactFizzConfig.dom-fb.js | 2 +- .../src/forks/ReactFizzConfig.dom-legacy.js | 2 +- .../src/forks/ReactFizzConfig.dom.js | 2 +- .../src/forks/ReactFizzConfig.markup.js | 2 +- .../src/forks/ReactFizzConfig.noop.js | 2 +- .../forks/ReactFlightServerConfig.custom.js | 4 +- ...ReactFlightServerConfig.dom-browser-esm.js | 4 +- .../ReactFlightServerConfig.dom-browser-fb.js | 4 +- ...ctFlightServerConfig.dom-browser-parcel.js | 4 +- ...lightServerConfig.dom-browser-turbopack.js | 4 +- .../ReactFlightServerConfig.dom-browser.js | 4 +- .../forks/ReactFlightServerConfig.dom-bun.js | 4 +- ...ReactFlightServerConfig.dom-edge-parcel.js | 4 +- ...ctFlightServerConfig.dom-edge-turbopack.js | 4 +- .../forks/ReactFlightServerConfig.dom-edge.js | 4 +- .../ReactFlightServerConfig.dom-legacy.js | 4 +- .../ReactFlightServerConfig.dom-node-esm.js | 2 +- .../ReactFlightServerConfig.dom-node-fb.js | 4 +- ...ReactFlightServerConfig.dom-node-parcel.js | 2 +- ...ctFlightServerConfig.dom-node-turbopack.js | 2 +- ...ctFlightServerConfig.dom-node-unbundled.js | 2 +- .../forks/ReactFlightServerConfig.dom-node.js | 2 +- .../forks/ReactFlightServerConfig.markup.js | 4 +- .../src/forks/ReactFlightServerConfig.noop.js | 4 +- .../src/ReactSuspenseTestUtils.js | 2 +- .../src/ReactFiberConfigTestHost.js | 4 +- .../src/ReactTestRenderer.js | 54 ++- packages/react/src/ReactAct.js | 4 +- packages/react/src/ReactCacheImpl.js | 4 +- packages/react/src/ReactChildren.js | 28 +- packages/react/src/ReactContext.js | 4 +- packages/react/src/ReactHooks.js | 2 +- packages/react/src/ReactLazy.js | 18 +- .../react/src/ReactSharedInternalsClient.js | 6 +- .../react/src/ReactSharedInternalsServer.js | 6 +- packages/react/src/ReactStartTransition.js | 4 +- packages/scheduler/src/forks/Scheduler.js | 4 +- .../scheduler/src/forks/SchedulerNative.js | 2 +- .../scheduler/src/forks/SchedulerPostTask.js | 2 +- packages/shared/CheckStringCoercion.js | 6 +- packages/shared/DefaultPrepareStackTrace.js | 2 +- .../shared/ReactPerformanceTrackProperties.js | 2 +- packages/shared/ReactSerializationErrors.js | 6 +- packages/shared/ReactSymbols.js | 4 +- .../forks/ReactFeatureFlags.native-fb.js | 4 +- .../forks/ReactFeatureFlags.native-oss.js | 2 +- .../forks/ReactFeatureFlags.test-renderer.js | 2 +- ...actFeatureFlags.test-renderer.native-fb.js | 2 +- .../ReactFeatureFlags.test-renderer.www.js | 2 +- .../shared/forks/ReactFeatureFlags.www.js | 2 +- packages/shared/getComponentNameFromType.js | 16 +- .../src/useSyncExternalStoreWithSelector.js | 4 +- scripts/flags/flags.js | 15 +- scripts/flow/environment.js | 40 +- yarn.lock | 36 +- 330 files changed, 2423 insertions(+), 2422 deletions(-) diff --git a/package.json b/package.json index c247d21d6c0d..db5b359c7a27 100644 --- a/package.json +++ b/package.json @@ -75,8 +75,8 @@ "eslint-plugin-react-internal": "link:./scripts/eslint-rules", "fbjs-scripts": "^3.0.1", "filesize": "^6.0.1", - "flow-bin": "^0.307.1", - "flow-remove-types": "^2.307.1", + "flow-bin": "^0.317.0", + "flow-remove-types": "^2.317.0", "flow-typed": "^4.1.1", "glob": "^7.1.6", "glob-stream": "^6.1.0", diff --git a/packages/react-cache/src/LRU.js b/packages/react-cache/src/LRU.js index 1ab1c96f9694..087503853e71 100644 --- a/packages/react-cache/src/LRU.js +++ b/packages/react-cache/src/LRU.js @@ -56,21 +56,21 @@ export function createLRU(limit: number): LRU { function deleteLeastRecentlyUsedEntries(targetSize: number) { // Delete entries from the cache, starting from the end of the list. if (first !== null) { - const resolvedFirst: Entry = (first: any); + const resolvedFirst: Entry = first as any; let last: null | Entry = resolvedFirst.previous; while (size > targetSize && last !== null) { const onDelete = last.onDelete; const previous = last.previous; - last.onDelete = (null: any); + last.onDelete = null as any; // Remove from the list - last.previous = last.next = (null: any); + last.previous = last.next = null as any; if (last === first) { // Reached the head of the list. first = last = null; } else { - (first: any).previous = previous; - previous.next = (first: any); + (first as any).previous = previous; + previous.next = first as any; last = previous; } @@ -88,8 +88,8 @@ export function createLRU(limit: number): LRU { const entry = { value, onDelete, - next: (null: any), - previous: (null: any), + next: null as any, + previous: null as any, }; if (first === null) { entry.previous = entry.next = entry; @@ -118,7 +118,7 @@ export function createLRU(limit: number): LRU { // $FlowFixMe[invalid-compare] if (next !== null) { // Entry already cached - const resolvedFirst: Entry = (first: any); + const resolvedFirst: Entry = first as any; if (first !== entry) { // Remove from current position const previous = entry.previous; diff --git a/packages/react-cache/src/ReactCacheOld.js b/packages/react-cache/src/ReactCacheOld.js index 7ea17286679d..5485505af7e2 100644 --- a/packages/react-cache/src/ReactCacheOld.js +++ b/packages/react-cache/src/ReactCacheOld.js @@ -107,14 +107,14 @@ function accessResult( thenable.then( value => { if (newResult.status === Pending) { - const resolvedResult: ResolvedResult = (newResult: any); + const resolvedResult: ResolvedResult = newResult as any; resolvedResult.status = Resolved; resolvedResult.value = value; } }, error => { if (newResult.status === Pending) { - const rejectedResult: RejectedResult = (newResult: any); + const rejectedResult: RejectedResult = newResult as any; rejectedResult.status = Rejected; rejectedResult.value = error; } @@ -128,7 +128,7 @@ function accessResult( entriesForResource.set(key, newEntry); return newResult; } else { - return (lru.access(entry): any); + return lru.access(entry) as any; } } @@ -147,7 +147,7 @@ export function unstable_createResource( maybeHashInput?: I => K, ): Resource { const hashInput: I => K = - maybeHashInput !== undefined ? maybeHashInput : (identityHashFn: any); + maybeHashInput !== undefined ? maybeHashInput : (identityHashFn as any); const resource = { read(input: I): V { @@ -171,7 +171,7 @@ export function unstable_createResource( } default: // Should be unreachable - return (undefined: any); + return undefined as any; } }, diff --git a/packages/react-client/src/ReactFlightClient.js b/packages/react-client/src/ReactFlightClient.js index e8af45adf713..7ac416bbe6b6 100644 --- a/packages/react-client/src/ReactFlightClient.js +++ b/packages/react-client/src/ReactFlightClient.js @@ -116,7 +116,7 @@ import type {SharedStateClient} from 'react/src/ReactSharedInternalsClient'; // client both in the RSC environment, in the SSR environments as well as the // browser client. We should probably have a separate RSC build. This is DEV // only though. -const ReactSharedInteralsServer: void | SharedStateServer = (React: any) +const ReactSharedInteralsServer: void | SharedStateServer = (React as any) .__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE; const ReactSharedInternals: SharedStateServer | SharedStateClient = React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE || @@ -254,7 +254,7 @@ function ReactPromise(status: any, value: any, reason: any) { } } // We subclass Promise.prototype so that we get other methods like .catch -ReactPromise.prototype = (Object.create(Promise.prototype): any); +ReactPromise.prototype = Object.create(Promise.prototype) as any; // TODO: This doesn't return a new Promise chain unlike the real .then ReactPromise.prototype.then = function ( this: SomeChunk, @@ -304,15 +304,15 @@ ReactPromise.prototype.then = function ( case BLOCKED: if (typeof resolve === 'function') { if (chunk.value === null) { - chunk.value = ([]: Array mixed)>); + chunk.value = [] as Array mixed)>; } chunk.value.push(resolve); } if (typeof reject === 'function') { if (chunk.reason === null) { - chunk.reason = ([]: Array< + chunk.reason = [] as Array< InitializationReference | (mixed => mixed), - >); + >; } chunk.reason.push(reject); } @@ -394,7 +394,7 @@ function unwrapWeakResponse(weakResponse: WeakResponse): Response { } return response; } else { - return (weakResponse: any); // In prod we just use the real Response directly. + return weakResponse as any; // In prod we just use the real Response directly. } } @@ -402,7 +402,7 @@ function getWeakResponse(response: Response): WeakResponse { if (__DEV__) { return response._weakResponse; } else { - return (response: any); // In prod we just use the real Response directly. + return response as any; // In prod we just use the real Response directly. } } @@ -437,7 +437,7 @@ function readChunk(chunk: SomeChunk): T { case BLOCKED: case HALTED: // eslint-disable-next-line no-throw-literal - throw ((chunk: any): Thenable); + throw chunk as any as Thenable; default: throw chunk.reason; } @@ -446,7 +446,7 @@ function readChunk(chunk: SomeChunk): T { export function getRoot(weakResponse: WeakResponse): Thenable { const response = unwrapWeakResponse(weakResponse); const chunk = getChunk(response, 0); - return (chunk: any); + return chunk as any; } function createPendingChunk(response: Response): PendingChunk { @@ -547,7 +547,7 @@ function moveDebugInfoFromChunkToInnerValue( debugInfo, ); } else if (!Object.isFrozen(resolvedValue)) { - Object.defineProperty((resolvedValue: any), '_debugInfo', { + Object.defineProperty(resolvedValue as any, '_debugInfo', { configurable: false, enumerable: false, writable: true, @@ -665,9 +665,9 @@ function wakeChunkIfInitialized( } } // The status might have changed after fulfilling the reference. - switch ((chunk: SomeChunk).status) { + switch ((chunk as SomeChunk).status) { case INITIALIZED: - const initializedChunk: InitializedChunk = (chunk: any); + const initializedChunk: InitializedChunk = chunk as any; wakeChunk( response, resolveListeners, @@ -721,7 +721,7 @@ function triggerErrorOnChunk( if (chunk.status !== PENDING && chunk.status !== BLOCKED) { // If we get more data to an already resolved ID, we assume that it's // a stream chunk since any other row shouldn't have more than one entry. - const streamChunk: InitializedStreamChunk = (chunk: any); + const streamChunk: InitializedStreamChunk = chunk as any; const controller = streamChunk.reason; // $FlowFixMe[incompatible-type]: The error method should accept mixed. controller.error(error); @@ -736,7 +736,7 @@ function triggerErrorOnChunk( const prevHandler = initializingHandler; const prevChunk = initializingChunk; initializingHandler = null; - const cyclicChunk: BlockedChunk = (chunk: any); + const cyclicChunk: BlockedChunk = chunk as any; cyclicChunk.status = BLOCKED; cyclicChunk.value = null; cyclicChunk.reason = null; @@ -761,7 +761,7 @@ function triggerErrorOnChunk( } } - const erroredChunk: ErroredChunk = (chunk: any); + const erroredChunk: ErroredChunk = chunk as any; erroredChunk.status = ERRORED; erroredChunk.reason = error; if (listeners !== null) { @@ -861,7 +861,7 @@ function resolveModelChunk( if (chunk.status !== PENDING) { // If we get more data to an already resolved ID, we assume that it's // a stream chunk since any other row shouldn't have more than one entry. - const streamChunk: InitializedStreamChunk = (chunk: any); + const streamChunk: InitializedStreamChunk = chunk as any; const controller = streamChunk.reason; controller.enqueueModel(value); return; @@ -869,7 +869,7 @@ function resolveModelChunk( releasePendingChunk(response, chunk); const resolveListeners = chunk.value; const rejectListeners = chunk.reason; - const resolvedChunk: ResolvedModelChunk = (chunk: any); + const resolvedChunk: ResolvedModelChunk = chunk as any; resolvedChunk.status = RESOLVED_MODEL; resolvedChunk.value = value; resolvedChunk.reason = response; @@ -895,7 +895,7 @@ function resolveModuleChunk( releasePendingChunk(response, chunk); const resolveListeners = chunk.value; const rejectListeners = chunk.reason; - const resolvedChunk: ResolvedModuleChunk = (chunk: any); + const resolvedChunk: ResolvedModuleChunk = chunk as any; resolvedChunk.status = RESOLVED_MODULE; resolvedChunk.value = value; resolvedChunk.reason = null; @@ -960,7 +960,7 @@ function initializeDebugChunk( } // Initializing the model for the first time. initializeModelChunk(debugChunk); - const initializedChunk = ((debugChunk: any): SomeChunk); + const initializedChunk = debugChunk as any as SomeChunk; switch (initializedChunk.status) { case INITIALIZED: { debugInfo[idx] = initializeDebugInfo( @@ -1028,7 +1028,7 @@ function initializeModelChunk(chunk: ResolvedModelChunk): void { // We go to the BLOCKED state until we've fully resolved this. // We do this before parsing in case we try to initialize the same chunk // while parsing the model. Such as in a cyclic reference. - const cyclicChunk: BlockedChunk = (chunk: any); + const cyclicChunk: BlockedChunk = chunk as any; cyclicChunk.status = BLOCKED; cyclicChunk.value = null; cyclicChunk.reason = null; @@ -1075,7 +1075,7 @@ function initializeModelChunk(chunk: ResolvedModelChunk): void { return; } } - const initializedChunk: InitializedChunk = (chunk: any); + const initializedChunk: InitializedChunk = chunk as any; initializedChunk.status = INITIALIZED; initializedChunk.value = value; initializedChunk.reason = null; @@ -1084,7 +1084,7 @@ function initializeModelChunk(chunk: ResolvedModelChunk): void { processChunkDebugInfo(response, initializedChunk, value); } } catch (error) { - const erroredChunk: ErroredChunk = (chunk: any); + const erroredChunk: ErroredChunk = chunk as any; erroredChunk.status = ERRORED; erroredChunk.reason = error; } finally { @@ -1098,12 +1098,12 @@ function initializeModelChunk(chunk: ResolvedModelChunk): void { function initializeModuleChunk(chunk: ResolvedModuleChunk): void { try { const value: T = requireModule(chunk.value); - const initializedChunk: InitializedChunk = (chunk: any); + const initializedChunk: InitializedChunk = chunk as any; initializedChunk.status = INITIALIZED; initializedChunk.value = value; initializedChunk.reason = null; } catch (error) { - const erroredChunk: ErroredChunk = (chunk: any); + const erroredChunk: ErroredChunk = chunk as any; erroredChunk.status = ERRORED; erroredChunk.reason = error; } @@ -1240,7 +1240,7 @@ function initializeElement( element._debugStack = normalizedStackTrace; let task: null | ConsoleTask = null; if (supportsCreateTask && stack !== null) { - const createTaskFn = (console: any).createTask.bind( + const createTaskFn = (console as any).createTask.bind( console, getTaskName(element.type), ); @@ -1322,19 +1322,19 @@ function createElement( let element: any; if (__DEV__) { // `ref` is non-enumerable in dev - element = ({ + element = { $$typeof: REACT_ELEMENT_TYPE, type, key, props, _owner: owner === undefined ? null : owner, - }: any); + } as any; Object.defineProperty(element, 'ref', { enumerable: false, get: nullRefGetter, }); } else { - element = ({ + element = { // This tag allows us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, @@ -1342,16 +1342,16 @@ function createElement( key, ref: null, props, - }: any); + } as any; } if (__DEV__) { // We don't really need to add any of these but keeping them for good measure. // Unfortunately, _store is enumerable in jest matchers so for equality to // work, I need to keep it or make _store non-enumerable in the other file. - element._store = ({}: { + element._store = {} as { validated?: number, - }); + }; Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, @@ -1463,7 +1463,7 @@ function getChunk(response: Response, id: number): SomeChunk { // For partial streams, chunks accessed after close should be HALTED // (never resolve). chunk = createPendingChunk(response); - const haltedChunk: HaltedChunk = (chunk: any); + const haltedChunk: HaltedChunk = chunk as any; haltedChunk.status = HALTED; haltedChunk.value = null; haltedChunk.reason = null; @@ -1673,7 +1673,7 @@ function fulfillReference( return; } const resolveListeners = chunk.value; - const initializedChunk: InitializedChunk = (chunk: any); + const initializedChunk: InitializedChunk = chunk as any; initializedChunk.status = INITIALIZED; initializedChunk.value = handler.value; initializedChunk.reason = handler.reason; // Used by streaming chunks @@ -1762,7 +1762,7 @@ function waitForReference( // If it's still pending that suggests that it was referencing an object in the debug // channel, but no debug channel was wired up so it's missing. In this case we can just // drop the debug info instead of halting the whole stream. - return (null: any); + return null as any; } } @@ -1805,7 +1805,7 @@ function waitForReference( } // Return a place holder value for now. - return (null: any); + return null as any; } function loadServerReference, T>( @@ -1840,7 +1840,7 @@ function loadServerReference, T>( let promise: null | Thenable = preloadModule(serverReference); if (!promise) { if (!metaData.bound) { - const resolvedValue = (requireModule(serverReference): any); + const resolvedValue = requireModule(serverReference) as any; registerBoundServerReference( resolvedValue, metaData.id, @@ -1871,11 +1871,11 @@ function loadServerReference, T>( } function fulfill(): void { - let resolvedValue = (requireModule(serverReference): any); + let resolvedValue = requireModule(serverReference) as any; if (metaData.bound) { // This promise is coming from us and should have initilialized by now. - const boundArgs: Array = (metaData.bound: any).value.slice(0); + const boundArgs: Array = (metaData.bound as any).value.slice(0); boundArgs.unshift(null); // this resolvedValue = resolvedValue.bind.apply(resolvedValue, boundArgs); } @@ -1927,7 +1927,7 @@ function loadServerReference, T>( return; } const resolveListeners = chunk.value; - const initializedChunk: InitializedChunk = (chunk: any); + const initializedChunk: InitializedChunk = chunk as any; initializedChunk.status = INITIALIZED; initializedChunk.value = handler.value; initializedChunk.reason = null; @@ -1990,7 +1990,7 @@ function loadServerReference, T>( promise.then(fulfill, reject); // Return a place holder value for now. - return (null: any); + return null as any; } function resolveLazy(value: any): mixed { @@ -2025,7 +2025,7 @@ function transferReferencedDebugInfo( for (let i = 0; i < referencedDebugInfo.length; ++i) { const debugInfoEntry = referencedDebugInfo[i]; if (debugInfoEntry.name != null) { - (debugInfoEntry: ReactComponentInfo); + debugInfoEntry as ReactComponentInfo; // We're not transferring Component info since we use Component info // in Debug info to fill in gaps between Fibers for the parent stack. } else { @@ -2112,7 +2112,7 @@ function getOutlinedModel( errored: false, }; } - return (null: any); + return null as any; } default: { // This is an error. Instead of erroring directly, we're going to encode this on @@ -2131,7 +2131,7 @@ function getOutlinedModel( errored: true, }; } - return (null: any); + return null as any; } } } @@ -2209,7 +2209,7 @@ function getOutlinedModel( errored: false, }; } - return (null: any); + return null as any; } default: // This is an error. Instead of erroring directly, we're going to encode this on @@ -2229,7 +2229,7 @@ function getOutlinedModel( }; } // Placeholder - return (null: any); + return null as any; } } @@ -2651,7 +2651,7 @@ function parseModelTuple( response: Response, value: {+[key: string]: JSONValue} | $ReadOnlyArray, ): any { - const tuple: [mixed, mixed, mixed, mixed] = (value: any); + const tuple: [mixed, mixed, mixed, mixed] = value as any; if (tuple[0] === REACT_ELEMENT_TYPE) { // TODO: Consider having React just directly accept these arrays as elements. @@ -2661,9 +2661,9 @@ function parseModelTuple( tuple[1], tuple[2], tuple[3], - __DEV__ ? (tuple: any)[4] : null, - __DEV__ ? (tuple: any)[5] : null, - __DEV__ ? (tuple: any)[6] : 0, + __DEV__ ? (tuple as any)[4] : null, + __DEV__ ? (tuple as any)[5] : null, + __DEV__ ? (tuple as any)[6] : 0, ); } return value; @@ -2730,7 +2730,7 @@ function ResponseInstance( ReactSharedInteralsServer === undefined || ReactSharedInteralsServer.A === null ? null - : (ReactSharedInteralsServer.A.getOwner(): any); + : (ReactSharedInteralsServer.A.getOwner() as any); this._debugRootOwner = rootOwner; this._debugRootStack = @@ -2746,7 +2746,7 @@ function ResponseInstance( // elements created by the server. We use the "use server" string to indicate that // this is where we enter the server from the client. // TODO: Make this string configurable. - this._debugRootTask = (console: any).createTask( + this._debugRootTask = (console as any).createTask( '"use ' + rootEnv.toLowerCase() + '"', ); } @@ -2850,19 +2850,19 @@ export function createStreamState( weakResponse: WeakResponse, // DEV-only streamDebugValue: mixed, // DEV-only ): StreamState { - const streamState: StreamState = (({ + const streamState: StreamState = { _rowState: 0, _rowID: 0, _rowTag: 0, _rowLength: 0, _buffer: [], - }: Omit): any); + } as Omit as any; if (__DEV__ && enableAsyncDebugInfo) { const response = unwrapWeakResponse(weakResponse); // Create an entry for the I/O to load the stream itself. const debugValuePromise = Promise.resolve(streamDebugValue); - (debugValuePromise: any).status = 'fulfilled'; - (debugValuePromise: any).value = streamDebugValue; + (debugValuePromise as any).status = 'fulfilled'; + (debugValuePromise as any).value = streamDebugValue; streamState._debugInfo = { name: 'rsc stream', start: response._debugStartTime, @@ -2896,7 +2896,7 @@ function incrementChunkDebugInfo( const debugInfo: ReactIOInfo = streamState._debugInfo; const endTime = performance.now(); const previousEndTime = debugInfo.end; - const newByteLength = ((debugInfo.byteSize: any): number) + chunkLength; + const newByteLength = (debugInfo.byteSize as any as number) + chunkLength; if ( newByteLength > streamState._debugTargetChunkSize || endTime > previousEndTime + 10 @@ -2942,7 +2942,7 @@ function addAsyncInfo(chunk: SomeChunk, asyncInfo: ReactAsyncInfo): void { } else if (!Object.isFrozen(value)) { // TODO: Debug info is dropped for frozen elements. See the TODO in // moveDebugInfoFromChunkToInnerValue. - Object.defineProperty((value: any), '_debugInfo', { + Object.defineProperty(value as any, '_debugInfo', { configurable: false, enumerable: false, writable: true, @@ -2988,7 +2988,7 @@ function resolveDebugHalt(response: Response, id: number): void { return; } releasePendingChunk(response, chunk); - const haltedChunk: HaltedChunk = (chunk: any); + const haltedChunk: HaltedChunk = chunk as any; haltedChunk.status = HALTED; haltedChunk.value = null; haltedChunk.reason = null; @@ -3030,7 +3030,7 @@ function resolveText( if (chunk && chunk.status !== PENDING) { // If we get more data to an already resolved ID, we assume that it's // a stream chunk since any other row shouldn't have more than one entry. - const streamChunk: InitializedStreamChunk = (chunk: any); + const streamChunk: InitializedStreamChunk = chunk as any; const controller = streamChunk.reason; controller.enqueueValue(text); return; @@ -3056,7 +3056,7 @@ function resolveBuffer( if (chunk && chunk.status !== PENDING) { // If we get more data to an already resolved ID, we assume that it's // a stream chunk since any other row shouldn't have more than one entry. - const streamChunk: InitializedStreamChunk = (chunk: any); + const streamChunk: InitializedStreamChunk = chunk as any; const controller = streamChunk.reason; controller.enqueueValue(buffer); return; @@ -3109,7 +3109,7 @@ function resolveModule( releasePendingChunk(response, chunk); // This can't actually happen because we don't have any forward // references to modules. - blockedChunk = (chunk: any); + blockedChunk = chunk as any; blockedChunk.status = BLOCKED; } if (__DEV__) { @@ -3171,7 +3171,7 @@ function resolveStream>( const prevHandler = initializingHandler; const prevChunk = initializingChunk; initializingHandler = null; - const cyclicChunk: BlockedChunk = (chunk: any); + const cyclicChunk: BlockedChunk = chunk as any; cyclicChunk.status = BLOCKED; cyclicChunk.value = null; cyclicChunk.reason = null; @@ -3198,12 +3198,12 @@ function resolveStream>( } } - const resolvedChunk: InitializedStreamChunk = (chunk: any); + const resolvedChunk: InitializedStreamChunk = chunk as any; resolvedChunk.status = INITIALIZED; resolvedChunk.value = stream; resolvedChunk.reason = controller; if (resolveListeners !== null) { - wakeChunk(response, resolveListeners, chunk.value, (chunk: any)); + wakeChunk(response, resolveListeners, chunk.value, chunk as any); } else { if (__DEV__) { processChunkDebugInfo(response, resolvedChunk, stream); @@ -3217,7 +3217,7 @@ function startReadableStream( type: void | 'bytes', streamState: StreamState, ): void { - let controller: ReadableStreamController = (null: any); + let controller: ReadableStreamController = null as any; let closed = false; const stream = new ReadableStream({ type: type, @@ -3252,7 +3252,7 @@ function startReadableStream( } else { chunk.then( v => controller.enqueue(v), - e => controller.error((e: any)), + e => controller.error(e as any), ); previousBlockedChunk = chunk; } @@ -3262,7 +3262,7 @@ function startReadableStream( const chunk: SomeChunk = createPendingChunk(response); chunk.then( v => controller.enqueue(v), - e => controller.error((e: any)), + e => controller.error(e as any), ); previousBlockedChunk = chunk; blockedChunk.then(function () { @@ -3301,7 +3301,7 @@ function startReadableStream( const blockedChunk = previousBlockedChunk; // We shouldn't get any more enqueues after this so we can set it back to null. previousBlockedChunk = null; - blockedChunk.then(() => controller.error((error: any))); + blockedChunk.then(() => controller.error(error as any)); } }, }; @@ -3323,7 +3323,7 @@ function createIterator( // TODO: The iterator could inherit the AsyncIterator prototype which is not exposed as // a global but exists as a prototype of an AsyncGenerator. However, it's not needed // to satisfy the iterable protocol. - (iterator: any)[ASYNC_ITERATOR] = asyncIterator; + (iterator as any)[ASYNC_ITERATOR] = asyncIterator; return iterator; } @@ -3345,13 +3345,13 @@ function startAsyncIterable( false, ); } else { - const chunk: PendingChunk> = (buffer[ + const chunk: PendingChunk> = buffer[ nextWriteIndex - ]: any); + ] as any; const resolveListeners = chunk.value; const rejectListeners = chunk.reason; const initializedChunk: InitializedChunk> = - (chunk: any); + chunk as any; initializedChunk.status = INITIALIZED; initializedChunk.value = {done: false, value: value}; initializedChunk.reason = null; @@ -3428,7 +3428,7 @@ function startAsyncIterable( }, }; - const iterable: $AsyncIterable = ({}: any); + const iterable: $AsyncIterable = {} as any; // $FlowFixMe[cannot-write] iterable[ASYNC_ITERATOR] = (): $AsyncIterator => { let nextReadIndex = 0; @@ -3484,7 +3484,7 @@ function stopStream( response._weakResponse.response = null; } } - const streamChunk: InitializedStreamChunk = (chunk: any); + const streamChunk: InitializedStreamChunk = chunk as any; const controller = streamChunk.reason; controller.close(row === '' ? '"$undefined"' : row); } @@ -3533,7 +3533,7 @@ function resolveErrorDev( cause: reviveModel( response, // $FlowFixMe[incompatible-type] -- Flow thinks `cause` in `cause?: JSONValue` can be undefined after `in` check. - (errorInfo.cause: JSONValue), + errorInfo.cause as JSONValue, errorInfo, 'cause', ), @@ -3547,7 +3547,7 @@ function resolveErrorDev( ? reviveModel( response, // $FlowFixMe[incompatible-type] - (errorInfo.errors: JSONValue), + errorInfo.errors as JSONValue, errorInfo, 'errors', ) @@ -3597,8 +3597,8 @@ function resolveErrorDev( error = ownerTask.run(callStack); } - (error: any).name = name; - (error: any).environmentName = env; + (error as any).name = name; + (error as any).environmentName = env; return error; } @@ -3617,8 +3617,8 @@ function resolveErrorModel( } else { error = resolveErrorProd(response); } - (error: any).digest = errorInfo.digest; - const errorWithDigest: ErrorWithDigest = (error: any); + (error as any).digest = errorInfo.digest; + const errorWithDigest: ErrorWithDigest = error as any; if (!chunk) { const newChunk: ErroredChunk = createErrorChunk( response, @@ -3645,12 +3645,12 @@ function resolveHint( dispatchHint(code, hintModel); } -const supportsCreateTask = __DEV__ && !!(console: any).createTask; +const supportsCreateTask = __DEV__ && !!(console as any).createTask; type FakeFunction = (() => T) => T; const fakeFunctionCache: Map> = __DEV__ ? new Map() - : (null: any); + : (null as any); let fakeFunctionIdx = 0; function createFakeFunction( @@ -3882,7 +3882,7 @@ function getRootTask( // If the root most owner component is itself in a different environment than the requested // environment then we create an extra task to indicate that we're transitioning into it. // Like if one environment just requests another environment. - const createTaskFn = (console: any).createTask.bind( + const createTaskFn = (console as any).createTask.bind( console, '"use ' + childEnvironmentName.toLowerCase() + '"', ); @@ -3935,10 +3935,10 @@ function initializeFakeTask( ? '"use ' + env.toLowerCase() + '"' : // Some unfortunate pattern matching to refine the type. debugInfo.key !== undefined - ? getServerComponentTaskName(((debugInfo: any): ReactComponentInfo)) + ? getServerComponentTaskName(debugInfo as any as ReactComponentInfo) : debugInfo.name !== undefined - ? getIOInfoTaskName(((debugInfo: any): ReactIOInfo)) - : getAsyncInfoTaskName(((debugInfo: any): ReactAsyncInfo)); + ? getIOInfoTaskName(debugInfo as any as ReactIOInfo) + : getAsyncInfoTaskName(debugInfo as any as ReactAsyncInfo); // $FlowFixMe[cannot-write]: We consider this part of initialization. return (debugInfo.debugTask = buildFakeTask( response, @@ -3958,7 +3958,7 @@ function buildFakeTask( env: string, useEnclosingLine: boolean, ): ConsoleTask { - const createTaskFn = (console: any).createTask.bind(console, taskName); + const createTaskFn = (console as any).createTask.bind(console, taskName); const callStack = buildFakeCallStack( response, stack, @@ -4003,8 +4003,8 @@ const createFakeJSXCallStackInDEV: ( ? // We use this technique to trick minifiers to preserve the function name. (createFakeJSXCallStack.react_stack_bottom_frame.bind( createFakeJSXCallStack, - ): any) - : (null: any); + ) as any) + : (null as any); /** @noinline */ function fakeJSXCallSite() { @@ -4120,7 +4120,7 @@ function resolveDebugModel( initializeDebugChunk(response, parentChunk); if ( __DEV__ && - ((debugChunk: any): SomeChunk).status === BLOCKED && + (debugChunk as any as SomeChunk).status === BLOCKED && (response._debugChannel === undefined || !response._debugChannel.hasReadable) ) { @@ -4167,7 +4167,7 @@ const replayConsoleWithCallStack = { const prevStack = ReactSharedInternals.getCurrentStack; ReactSharedInternals.getCurrentStack = getCurrentStackInDEV; currentOwnerInDEV = - owner === null ? (response._debugRootOwner: any) : owner; + owner === null ? (response._debugRootOwner as any) : owner; try { const callStack = buildFakeCallStack( @@ -4205,8 +4205,8 @@ const replayConsoleWithCallStackInDEV: ( ? // We use this technique to trick minifiers to preserve the function name. (replayConsoleWithCallStack.react_stack_bottom_frame.bind( replayConsoleWithCallStack, - ): any) - : (null: any); + ) as any) + : (null as any); type ConsoleEntry = [ string, @@ -4290,7 +4290,7 @@ function initializeIOInfo(response: Response, ioInfo: ReactIOInfo): void { const env = response._rootEnvironmentName; const promise = ioInfo.value; if (promise) { - const thenable: Thenable = (promise: any); + const thenable: Thenable = promise as any; switch (thenable.status) { case INITIALIZED: logIOInfo(ioInfo, env, thenable.value); @@ -4621,7 +4621,7 @@ function flushComponentPerformance( const env = response._rootEnvironmentName; const promise = asyncInfo.awaited.value; if (promise) { - const thenable: Thenable = (promise: any); + const thenable: Thenable = promise as any; switch (thenable.status) { case INITIALIZED: logComponentAwait( @@ -4889,7 +4889,7 @@ function processFullStringRow( return; } case 72 /* "H" */: { - const code: HintCode = (row[0]: any); + const code: HintCode = row[0] as any; resolveHint(response, code, row.slice(1)); return; } @@ -5323,7 +5323,7 @@ function reviveModel( } if (isArray(value)) { for (let i = 0; i < value.length; i++) { - (value: any)[i] = reviveModel(response, value[i], value, '' + i); + (value as any)[i] = reviveModel(response, value[i], value, '' + i); } // $FlowFixMe[invalid-compare] if (value[0] === REACT_ELEMENT_TYPE) { @@ -5335,13 +5335,13 @@ function reviveModel( // Plain object for (const k in value) { if (k === __PROTO__) { - delete (value: any)[k]; + delete (value as any)[k]; } else { - const walked = reviveModel(response, (value: any)[k], value, k); + const walked = reviveModel(response, (value as any)[k], value, k); if (walked !== undefined) { - (value: any)[k] = walked; + (value as any)[k] = walked; } else { - delete (value: any)[k]; + delete (value as any)[k]; } } } @@ -5366,7 +5366,7 @@ export function close(weakResponse: WeakResponse): void { // Clear listeners to release closures and transition to HALTED. // Future .then() calls on HALTED chunks are no-ops. releasePendingChunk(response, chunk); - const haltedChunk: HaltedChunk = (chunk: any); + const haltedChunk: HaltedChunk = chunk as any; haltedChunk.status = HALTED; haltedChunk.value = null; haltedChunk.reason = null; diff --git a/packages/react-client/src/ReactFlightReplyClient.js b/packages/react-client/src/ReactFlightReplyClient.js index 150144c01065..0a4b0edce8e4 100644 --- a/packages/react-client/src/ReactFlightReplyClient.js +++ b/packages/react-client/src/ReactFlightReplyClient.js @@ -415,7 +415,7 @@ export function processReply( } if (typeof value === 'object') { - switch ((value: any).$$typeof) { + switch ((value as any).$$typeof) { case REACT_ELEMENT_TYPE: { if (temporaryReferences !== undefined && key.indexOf(':') === -1) { // TODO: If the property name contains a colon, we don't dedupe. Escape instead. @@ -445,7 +445,7 @@ export function processReply( } case REACT_LAZY_TYPE: { // Resolve lazy as if it wasn't here. In the future this will be encoded as a Promise. - const lazy: LazyComponent = (value: any); + const lazy: LazyComponent = value as any; const payload = lazy._payload; const init = lazy._init; if (formData === null) { @@ -472,7 +472,7 @@ export function processReply( // Suspended pendingParts++; const lazyId = nextPartId++; - const thenable: Thenable = (x: any); + const thenable: Thenable = x as any; const retry = function () { // While the first promise resolved, its value isn't necessarily what we'll // resolve into because we might suspend again. @@ -529,7 +529,7 @@ export function processReply( const promiseId = nextPartId++; const promiseReference = serializePromiseID(promiseId); writtenObjects.set(value, promiseReference); - const thenable: Thenable = (value: any); + const thenable: Thenable = value as any; thenable.then( partValue => { try { @@ -702,7 +702,7 @@ export function processReply( // Iterator, not Iterable const iteratorId = nextPartId++; const partJSON = serializeModel( - Array.from((iterator: any)), + Array.from(iterator as any), iteratorId, ); if (formData === null) { @@ -711,7 +711,7 @@ export function processReply( formData.append(formFieldPrefix + iteratorId, partJSON); return serializeIteratorID(iteratorId); } - return Array.from((iterator: any)); + return Array.from(iterator as any); } // TODO: ReadableStream is not available in old Node. Remove the typeof check later. @@ -721,13 +721,14 @@ export function processReply( ) { return serializeReadableStream(value); } - const getAsyncIterator: void | (() => $AsyncIterator) = - (value: any)[ASYNC_ITERATOR]; + const getAsyncIterator: void | (() => $AsyncIterator) = ( + value as any + )[ASYNC_ITERATOR]; if (typeof getAsyncIterator === 'function') { // We treat AsyncIterables as a Fragment and as such we might need to key them. return serializeAsyncIterable( - (value: any), - getAsyncIterator.call((value: any)), + value as any, + getAsyncIterator.call(value as any), ); } @@ -749,7 +750,7 @@ export function processReply( return serializeTemporaryReferenceMarker(); } if (__DEV__) { - if ((value: any).$$typeof === REACT_CONTEXT_TYPE) { + if ((value as any).$$typeof === REACT_CONTEXT_TYPE) { console.error( 'React Context Providers cannot be passed to Server Functions from the Client.%s', describeObjectForErrorMessage(parent, key), @@ -945,13 +946,13 @@ function encodeFormData(reference: any): Thenable { data.append('0', body); body = data; } - const fulfilled: FulfilledThenable = (thenable: any); + const fulfilled: FulfilledThenable = thenable as any; fulfilled.status = 'fulfilled'; fulfilled.value = body; resolve(body); }, e => { - const rejected: RejectedThenable = (thenable: any); + const rejected: RejectedThenable = thenable as any; rejected.status = 'rejected'; rejected.reason = e; reject(e); @@ -1023,7 +1024,7 @@ function customEncodeFormAction( 'This is a bug in React.', ); } - let boundPromise: Promise> = (referenceClosure.bound: any); + let boundPromise: Promise> = referenceClosure.bound as any; // $FlowFixMe[invalid-compare] if (boundPromise === null) { boundPromise = Promise.resolve([]); @@ -1072,18 +1073,18 @@ function isSignatureEqual( // Only instrument the thenable if the status if not defined. } else { const pendingThenable: PendingThenable> = - (boundPromise: any); + boundPromise as any; pendingThenable.status = 'pending'; pendingThenable.then( (boundArgs: Array) => { const fulfilledThenable: FulfilledThenable> = - (boundPromise: any); + boundPromise as any; fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = boundArgs; }, (error: mixed) => { const rejectedThenable: RejectedThenable = - (boundPromise: any); + boundPromise as any; rejectedThenable.status = 'rejected'; rejectedThenable.reason = error; }, @@ -1220,7 +1221,7 @@ export function registerBoundServerReference( encodeFormAction, ); }; - Object.defineProperties((reference: any), { + Object.defineProperties(reference as any, { $$FORM_ACTION: {value: $$FORM_ACTION}, $$IS_SIGNATURE_EQUAL: {value: isSignatureEqual}, bind: {value: bind}, @@ -1266,7 +1267,7 @@ function bind(this: Function): Function { const args = ArraySlice.call(arguments, 1); let boundPromise = null; if (referenceClosure.bound !== null) { - boundPromise = Promise.resolve((referenceClosure.bound: any)).then( + boundPromise = Promise.resolve(referenceClosure.bound as any).then( boundArgs => boundArgs.concat(args), ); } else { @@ -1284,7 +1285,7 @@ function bind(this: Function): Function { // $FlowFixMe[constant-condition] if (usedWithSSR) { // Only expose this in builds that would actually use it. Not needed on the client. - Object.defineProperties((newFn: any), { + Object.defineProperties(newFn as any, { $$FORM_ACTION: {value: this.$$FORM_ACTION}, $$IS_SIGNATURE_EQUAL: {value: isSignatureEqual}, bind: {value: bind}, @@ -1326,7 +1327,7 @@ export function createBoundServerReference, T>( } // Since this is a fake Promise whose .then doesn't chain, we have to wrap it. // TODO: Remove the wrapper once that's fixed. - return ((Promise.resolve(p): any): Promise>).then( + return (Promise.resolve(p) as any as Promise>).then( function (boundArgs) { return callServer(id, boundArgs.concat(args)); }, diff --git a/packages/react-client/src/ReactFlightTemporaryReferences.js b/packages/react-client/src/ReactFlightTemporaryReferences.js index 5ad92b3a1063..c259942f9aa0 100644 --- a/packages/react-client/src/ReactFlightTemporaryReferences.js +++ b/packages/react-client/src/ReactFlightTemporaryReferences.js @@ -27,5 +27,5 @@ export function readTemporaryReference( set: TemporaryReferenceSet, reference: string, ): T { - return (set.get(reference): any); + return set.get(reference) as any; } diff --git a/packages/react-debug-tools/src/ReactDebugHooks.js b/packages/react-debug-tools/src/ReactDebugHooks.js index c288b7851f58..585205e02c6e 100644 --- a/packages/react-debug-tools/src/ReactDebugHooks.js +++ b/packages/react-debug-tools/src/ReactDebugHooks.js @@ -74,7 +74,7 @@ function getPrimitiveStackCache(): Map> { let readHookLog; try { // Use all hooks here to add them to the hook log. - Dispatcher.useContext(({_currentValue: null}: any)); + Dispatcher.useContext({_currentValue: null} as any); Dispatcher.useState(null); Dispatcher.useReducer((s: mixed, a: mixed) => s, null); Dispatcher.useRef(null); @@ -106,23 +106,19 @@ function getPrimitiveStackCache(): Map> { } if (typeof Dispatcher.use === 'function') { // This type check is for Flow only. - Dispatcher.use( - ({ - $$typeof: REACT_CONTEXT_TYPE, - _currentValue: null, - }: any), - ); + Dispatcher.use({ + $$typeof: REACT_CONTEXT_TYPE, + _currentValue: null, + } as any); Dispatcher.use({ then() {}, status: 'fulfilled', value: null, }); try { - Dispatcher.use( - ({ - then() {}, - }: any), - ); + Dispatcher.use({ + then() {}, + } as any); } catch (x) {} } @@ -174,7 +170,7 @@ function readContext(context: ReactContext): T { // For now we don't expose readContext usage in the hooks debugging info. if (hasOwnProperty.call(currentContextDependency, 'memoizedValue')) { // $FlowFixMe[incompatible-use] Flow thinks `hasOwnProperty` mutates `currentContextDependency` - value = ((currentContextDependency.memoizedValue: any): T); + value = currentContextDependency.memoizedValue as any as T; // $FlowFixMe[incompatible-use] Flow thinks `hasOwnProperty` mutates `currentContextDependency` currentContextDependency = currentContextDependency.next; @@ -211,7 +207,7 @@ function use(usable: Usable): T { currentThenableState !== null && currentThenableIndex < currentThenableState.length ? currentThenableState[currentThenableIndex++] - : (usable: any); + : (usable as any); switch (thenable.status) { case 'fulfilled': { @@ -245,7 +241,7 @@ function use(usable: Usable): T { }); throw SuspenseException; } else if (usable.$$typeof === REACT_CONTEXT_TYPE) { - const context: ReactContext = (usable: any); + const context: ReactContext = usable as any; const value = readContext(context); hookLog.push({ @@ -310,7 +306,7 @@ function useReducer( if (hook !== null) { state = hook.memoizedState; } else { - state = init !== undefined ? init(initialArg) : ((initialArg: any): S); + state = init !== undefined ? init(initialArg) : (initialArg as any as S); } hookLog.push({ displayName: null, @@ -608,7 +604,7 @@ function useFormState( // $FlowFixMe[method-unbinding] typeof actionResult.then === 'function' ) { - const thenable: Thenable> = (actionResult: any); + const thenable: Thenable> = actionResult as any; switch (thenable.status) { case 'fulfilled': { value = thenable.value; @@ -630,7 +626,7 @@ function useFormState( value = thenable; } } else { - value = (actionResult: any); + value = actionResult as any; } } else { value = initialState; @@ -651,7 +647,7 @@ function useFormState( // value being a Thenable is equivalent to error being not null // i.e. we only reach this point with Awaited - const state = ((value: any): Awaited); + const state = value as any as Awaited; // TODO: support displaying pending value return [state, (payload: P) => {}, false]; @@ -678,7 +674,7 @@ function useActionState( // $FlowFixMe[method-unbinding] typeof actionResult.then === 'function' ) { - const thenable: Thenable> = (actionResult: any); + const thenable: Thenable> = actionResult as any; switch (thenable.status) { case 'fulfilled': { value = thenable.value; @@ -700,7 +696,7 @@ function useActionState( value = thenable; } } else { - value = (actionResult: any); + value = actionResult as any; } } else { value = initialState; @@ -721,7 +717,7 @@ function useActionState( // value being a Thenable is equivalent to error being not null // i.e. we only reach this point with Awaited - const state = ((value: any): Awaited); + const state = value as any as Awaited; // TODO: support displaying pending value return [state, (payload: P) => {}, false]; @@ -731,10 +727,10 @@ function useHostTransitionStatus(): TransitionStatus { const status = readContext( // $FlowFixMe[prop-missing] `readContext` only needs _currentValue // $FlowFixMe[incompatible-type] - ({ + { // $FlowFixMe[incompatible-type] TODO: Incorrect bottom value without access to Fiber config. _currentValue: null, - }: ReactContext), + } as ReactContext, ); hookLog.push({ @@ -1228,7 +1224,7 @@ export function inspectHooks( } const rootStack = ancestorStackError === undefined - ? ([]: ParsedStackFrame[]) + ? ([] as Array) : ErrorStackParser.parse(ancestorStackError); return buildTree(rootStack, readHookLog); } @@ -1238,9 +1234,9 @@ function setupContexts(contextMap: Map, any>, fiber: Fiber) { while (current) { if (current.tag === ContextProvider) { let context: ReactContext = current.type; - if ((context: any)._context !== undefined) { + if ((context as any)._context !== undefined) { // Support inspection of pre-19+ providers. - context = (context: any)._context; + context = (context as any)._context; } if (!contextMap.has(context)) { // Store the current value that we're going to restore later. @@ -1279,7 +1275,7 @@ function inspectHooksOfForwardRef( } const rootStack = ancestorStackError === undefined - ? ([]: ParsedStackFrame[]) + ? ([] as Array) : ErrorStackParser.parse(ancestorStackError); return buildTree(rootStack, readHookLog); } @@ -1324,7 +1320,7 @@ export function inspectHooksOfFiber( // Set up the current hook so that we can step through and read the // current state from them. - currentHook = (fiber.memoizedState: Hook); + currentHook = fiber.memoizedState as Hook; currentFiber = fiber; const thenableState = fiber.dependencies && fiber.dependencies._debugThenableState; @@ -1341,17 +1337,17 @@ export function inspectHooksOfFiber( currentContextDependency = dependencies !== null ? dependencies.firstContext : null; } else if (hasOwnProperty.call(currentFiber, 'dependencies_old')) { - const dependencies: Dependencies = (currentFiber: any).dependencies_old; + const dependencies: Dependencies = (currentFiber as any).dependencies_old; currentContextDependency = // $FlowFixMe[invalid-compare] dependencies !== null ? dependencies.firstContext : null; } else if (hasOwnProperty.call(currentFiber, 'dependencies_new')) { - const dependencies: Dependencies = (currentFiber: any).dependencies_new; + const dependencies: Dependencies = (currentFiber as any).dependencies_new; currentContextDependency = // $FlowFixMe[invalid-compare] dependencies !== null ? dependencies.firstContext : null; } else if (hasOwnProperty.call(currentFiber, 'contextDependencies')) { - const contextDependencies = (currentFiber: any).contextDependencies; + const contextDependencies = (currentFiber as any).contextDependencies; currentContextDependency = contextDependencies !== null ? contextDependencies.first : null; } else { diff --git a/packages/react-devtools-core/src/backend.js b/packages/react-devtools-core/src/backend.js index 5e70a178bace..7367e7bd1bc2 100644 --- a/packages/react-devtools-core/src/backend.js +++ b/packages/react-devtools-core/src/backend.js @@ -99,7 +99,7 @@ export function connectToDevTools(options: ?ConnectOptions) { useHttps = false, port = 8097, websocket, - resolveRNStyle = (null: $FlowFixMe), + resolveRNStyle = null as $FlowFixMe, retryConnectionDelay = 2000, isAppActive = () => true, onSettingsUpdated, @@ -217,7 +217,7 @@ export function connectToDevTools(options: ?ConnectOptions) { bridge, agent, // $FlowFixMe[constant-condition] - ((resolveRNStyle || hook.resolveRNStyle: any): ResolveNativeStyle), + (resolveRNStyle || hook.resolveRNStyle) as any as ResolveNativeStyle, nativeStyleEditorValidAttributes || hook.nativeStyleEditorValidAttributes || null, @@ -241,36 +241,28 @@ export function connectToDevTools(options: ?ConnectOptions) { }; if (!hook.hasOwnProperty('resolveRNStyle')) { - Object.defineProperty( - hook, - 'resolveRNStyle', - ({ - enumerable: false, - get() { - return lazyResolveRNStyle; - }, - set(value: $FlowFixMe) { - lazyResolveRNStyle = value; - initAfterTick(); - }, - }: Object), - ); + Object.defineProperty(hook, 'resolveRNStyle', { + enumerable: false, + get() { + return lazyResolveRNStyle; + }, + set(value: $FlowFixMe) { + lazyResolveRNStyle = value; + initAfterTick(); + }, + } as Object); } if (!hook.hasOwnProperty('nativeStyleEditorValidAttributes')) { - Object.defineProperty( - hook, - 'nativeStyleEditorValidAttributes', - ({ - enumerable: false, - get() { - return lazyNativeStyleEditorValidAttributes; - }, - set(value: $FlowFixMe) { - lazyNativeStyleEditorValidAttributes = value; - initAfterTick(); - }, - }: Object), - ); + Object.defineProperty(hook, 'nativeStyleEditorValidAttributes', { + enumerable: false, + get() { + return lazyNativeStyleEditorValidAttributes; + }, + set(value: $FlowFixMe) { + lazyNativeStyleEditorValidAttributes = value; + initAfterTick(); + }, + } as Object); } } }; @@ -311,7 +303,7 @@ export function connectToDevTools(options: ?ConnectOptions) { } } catch (e) { console.error( - '[React DevTools] Failed to parse JSON: ' + (event.data: any), + '[React DevTools] Failed to parse JSON: ' + (event.data as any), ); return; } diff --git a/packages/react-devtools-core/src/standalone.js b/packages/react-devtools-core/src/standalone.js index 6d32f18c4851..3e2538d47750 100644 --- a/packages/react-devtools-core/src/standalone.js +++ b/packages/react-devtools-core/src/standalone.js @@ -32,7 +32,7 @@ export type StatusTypes = 'server-connected' | 'devtools-connected' | 'error'; export type StatusListener = (message: string, status: StatusTypes) => void; export type OnDisconnectedCallback = () => void; -let node: HTMLElement = ((null: any): HTMLElement); +let node: HTMLElement = null as any as HTMLElement; let nodeWaitingToConnectHTML: string = ''; let projectRoots: Array = []; let statusListener: StatusListener = ( @@ -112,11 +112,11 @@ function reload() { root = createRoot(node); root.render( createElement(DevTools, { - bridge: ((bridge: any): FrontendBridge), + bridge: bridge as any as FrontendBridge, canViewElementSourceFunction, hookNamesModuleLoaderFunction, showTabBar: true, - store: ((store: any): Store), + store: store as any as Store, warnIfLegacyBackendDetected: true, viewElementSourceFunction, fetchFileWithCaching, @@ -263,7 +263,7 @@ function initialize(socket: WebSocket) { } }, }); - ((bridge: any): FrontendBridge).addListener('shutdown', () => { + (bridge as any as FrontendBridge).addListener('shutdown', () => { socket.close(); }); diff --git a/packages/react-devtools-extensions/src/main/index.js b/packages/react-devtools-extensions/src/main/index.js index 5954460edb68..1edbbf5e1cd3 100644 --- a/packages/react-devtools-extensions/src/main/index.js +++ b/packages/react-devtools-extensions/src/main/index.js @@ -486,10 +486,10 @@ function performInTabNavigationCleanup() { // Do not clean mostRecentOverrideTab on purpose, so we remember last opened // React DevTools tab, when user does in-tab navigation - store = (null: $FlowFixMe); - bridge = (null: $FlowFixMe); - render = (null: $FlowFixMe); - root = (null: $FlowFixMe); + store = null as $FlowFixMe; + bridge = null as $FlowFixMe; + render = null as $FlowFixMe; + root = null as $FlowFixMe; } function performFullCleanup() { @@ -511,15 +511,15 @@ function performFullCleanup() { componentsPortalContainer = null; profilerPortalContainer = null; suspensePortalContainer = null; - root = (null: $FlowFixMe); + root = null as $FlowFixMe; mostRecentOverrideTab = null; - store = (null: $FlowFixMe); - bridge = (null: $FlowFixMe); - render = (null: $FlowFixMe); + store = null as $FlowFixMe; + bridge = null as $FlowFixMe; + render = null as $FlowFixMe; port?.disconnect(); - port = (null: $FlowFixMe); + port = null as $FlowFixMe; } function connectExtensionPort(): void { @@ -546,7 +546,7 @@ function connectExtensionPort(): void { // so, when we call `port.disconnect()` from this script, // this should not trigger this callback and port reconnection port.onDisconnect.addListener(() => { - port = (null: $FlowFixMe); + port = null as $FlowFixMe; connectExtensionPort(); }); } @@ -599,9 +599,9 @@ function mountReactDevToolsWhenReactHasLoaded() { ); } -let bridge: FrontendBridge = (null: $FlowFixMe); +let bridge: FrontendBridge = null as $FlowFixMe; let lastSubscribedBridgeListener = null; -let store: Store = (null: $FlowFixMe); +let store: Store = null as $FlowFixMe; let profilingData = null; @@ -617,12 +617,12 @@ let editorPortalContainer = null; let inspectedElementPortalContainer = null; let mostRecentOverrideTab: null | TabID = null; -let render: (overrideTab?: TabID) => void = (null: $FlowFixMe); -let root: RootType = (null: $FlowFixMe); +let render: (overrideTab?: TabID) => void = null as $FlowFixMe; +let root: RootType = null as $FlowFixMe; let currentSelectedSource: null | SourceSelection = null; -let port: ExtensionRuntimePort = (null: $FlowFixMe); +let port: ExtensionRuntimePort = null as $FlowFixMe; // In case when multiple navigation events emitted in a short period of time // This debounced callback primarily used to avoid mounting React DevTools multiple times, which results diff --git a/packages/react-devtools-inline/src/backend.js b/packages/react-devtools-inline/src/backend.js index 9810d5b39ccf..8b0ab3584325 100644 --- a/packages/react-devtools-inline/src/backend.js +++ b/packages/react-devtools-inline/src/backend.js @@ -109,7 +109,7 @@ export function createBridge(contentWindow: any, wall?: Wall): BackendBridge { }; } - return (new Bridge(wall): BackendBridge); + return new Bridge(wall) as BackendBridge; } export function initialize(contentWindow: any): void { diff --git a/packages/react-devtools-inline/src/frontend.js b/packages/react-devtools-inline/src/frontend.js index b8d1b2ef4d81..28fe70b1b299 100644 --- a/packages/react-devtools-inline/src/frontend.js +++ b/packages/react-devtools-inline/src/frontend.js @@ -40,7 +40,7 @@ export function createBridge(contentWindow: any, wall?: Wall): FrontendBridge { }; } - return (new Bridge(wall): FrontendBridge); + return new Bridge(wall) as FrontendBridge; } export function initialize( @@ -58,7 +58,7 @@ export function initialize( } // Type refinement. - const frontendBridge = ((bridge: any): FrontendBridge); + const frontendBridge = bridge as any as FrontendBridge; if (store == null) { store = createStore(frontendBridge); diff --git a/packages/react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor.js b/packages/react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor.js index 7a8bfff43bf2..8b9db86fcc7a 100644 --- a/packages/react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor.js +++ b/packages/react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor.js @@ -97,14 +97,11 @@ function measureStyle( ) { const data = agent.getInstanceAndStyle({id, rendererID}); if (!data || !data.style) { - bridge.send( - 'NativeStyleEditor_styleAndLayout', - ({ - id, - layout: null, - style: null, - }: StyleAndLayout), - ); + bridge.send('NativeStyleEditor_styleAndLayout', { + id, + layout: null, + style: null, + } as StyleAndLayout); return; } @@ -119,14 +116,11 @@ function measureStyle( } if (!instance || typeof instance.measure !== 'function') { - bridge.send( - 'NativeStyleEditor_styleAndLayout', - ({ - id, - layout: null, - style: resolvedStyle || null, - }: StyleAndLayout), - ); + bridge.send('NativeStyleEditor_styleAndLayout', { + id, + layout: null, + style: resolvedStyle || null, + } as StyleAndLayout); return; } @@ -134,14 +128,11 @@ function measureStyle( // RN Android sometimes returns undefined here. Don't send measurements in this case. // https://github.com/jhen0409/react-native-debugger/issues/84#issuecomment-304611817 if (typeof x !== 'number') { - bridge.send( - 'NativeStyleEditor_styleAndLayout', - ({ - id, - layout: null, - style: resolvedStyle || null, - }: StyleAndLayout), - ); + bridge.send('NativeStyleEditor_styleAndLayout', { + id, + layout: null, + style: resolvedStyle || null, + } as StyleAndLayout); return; } const margin = @@ -150,23 +141,20 @@ function measureStyle( const padding = (resolvedStyle != null && resolveBoxStyle('padding', resolvedStyle)) || EMPTY_BOX_STYLE; - bridge.send( - 'NativeStyleEditor_styleAndLayout', - ({ - id, - layout: { - x, - y, - width, - height, - left, - top, - margin, - padding, - }, - style: resolvedStyle || null, - }: StyleAndLayout), - ); + bridge.send('NativeStyleEditor_styleAndLayout', { + id, + layout: { + x, + y, + width, + height, + left, + top, + margin, + padding, + }, + style: resolvedStyle || null, + } as StyleAndLayout); }); } @@ -194,7 +182,7 @@ function renameStyle( const {instance, style} = data; const newStyle = newName - ? {[oldName]: (undefined: string | void), [newName]: value} + ? {[oldName]: undefined as string | void, [newName]: value} : {[oldName]: undefined}; let customStyle; diff --git a/packages/react-devtools-shared/src/backend/StyleX/utils.js b/packages/react-devtools-shared/src/backend/StyleX/utils.js index ad137c7184e5..1c7769c51d6c 100644 --- a/packages/react-devtools-shared/src/backend/StyleX/utils.js +++ b/packages/react-devtools-shared/src/backend/StyleX/utils.js @@ -82,7 +82,7 @@ function crawlObjectProperties( function getPropertyValueForStyleName(styleName: string): string | null { if (cachedStyleNameToValueMap.has(styleName)) { - return ((cachedStyleNameToValueMap.get(styleName): any): string); + return cachedStyleNameToValueMap.get(styleName) as any as string; } for ( @@ -90,9 +90,9 @@ function getPropertyValueForStyleName(styleName: string): string | null { styleSheetIndex < document.styleSheets.length; styleSheetIndex++ ) { - const styleSheet = ((document.styleSheets[ + const styleSheet = document.styleSheets[ styleSheetIndex - ]: any): CSSStyleSheet); + ] as any as CSSStyleSheet; let rules: CSSRuleList | null = null; // this might throw if CORS rules are enforced https://www.w3.org/TR/cssom-1/#the-cssstylesheet-interface try { @@ -105,7 +105,7 @@ function getPropertyValueForStyleName(styleName: string): string | null { if (!(rules[ruleIndex] instanceof CSSStyleRule)) { continue; } - const rule = ((rules[ruleIndex]: any): CSSStyleRule); + const rule = rules[ruleIndex] as any as CSSStyleRule; const {cssText, selectorText, style} = rule; if (selectorText != null) { diff --git a/packages/react-devtools-shared/src/backend/agent.js b/packages/react-devtools-shared/src/backend/agent.js index 73fb202ad4e0..be566b4c4d35 100644 --- a/packages/react-devtools-shared/src/backend/agent.js +++ b/packages/react-devtools-shared/src/backend/agent.js @@ -226,9 +226,9 @@ function mergeRoots( } const leftSuspendedBy: DehydratedData = left.suspendedBy; - const {data, cleaned, unserializable} = (right.suspendedBy: DehydratedData); - const leftSuspendedByData = ((leftSuspendedBy.data: any): Array); - const rightSuspendedByData = ((data: any): Array); + const {data, cleaned, unserializable} = right.suspendedBy as DehydratedData; + const leftSuspendedByData = leftSuspendedBy.data as any as Array; + const rightSuspendedByData = data as any as Array; for (let i = 0; i < rightSuspendedByData.length; i++) { leftSuspendedByData.push(rightSuspendedByData[i]); } @@ -464,9 +464,9 @@ export default class Agent extends EventEmitter<{ if (isReactNativeEnvironment() || typeof target.nodeType !== 'number') { // In React Native or non-DOM we simply pick any renderer that has a match. for (const rendererID in this._rendererInterfaces) { - const renderer = ((this._rendererInterfaces[ - (rendererID: any) - ]: any): RendererInterface); + const renderer = this._rendererInterfaces[ + rendererID as any + ] as any as RendererInterface; try { const id = onlySuspenseNodes ? renderer.getSuspenseNodeIDForHostInstance(target) @@ -491,11 +491,11 @@ export default class Agent extends EventEmitter<{ let bestRendererID: number = 0; // Find the nearest ancestor which is mounted by a React. for (const rendererID in this._rendererInterfaces) { - const renderer = ((this._rendererInterfaces[ - (rendererID: any) - ]: any): RendererInterface); + const renderer = this._rendererInterfaces[ + rendererID as any + ] as any as RendererInterface; const nearestNode: null | Element = renderer.getNearestMountedDOMNode( - (target: any), + target as any, ); if (nearestNode !== null) { if (nearestNode === target) { @@ -537,9 +537,9 @@ export default class Agent extends EventEmitter<{ getComponentNameForHostInstance(target: HostInstance): string | null { const match = this.getIDForHostInstance(target); if (match !== null) { - const renderer = ((this._rendererInterfaces[ - (match.rendererID: any) - ]: any): RendererInterface); + const renderer = this._rendererInterfaces[ + match.rendererID as any + ] as any as RendererInterface; return renderer.getDisplayNameForElementID(match.id); } return null; @@ -575,7 +575,7 @@ export default class Agent extends EventEmitter<{ console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { const owners = renderer.getOwnersList(id); - this._bridge.send('ownersList', ({id, owners}: OwnersList)); + this._bridge.send('ownersList', {id, owners} as OwnersList); } }; @@ -653,9 +653,9 @@ export default class Agent extends EventEmitter<{ } for (const rendererID in this._rendererInterfaces) { - const renderer = ((this._rendererInterfaces[ - (rendererID: any) - ]: any): RendererInterface); + const renderer = this._rendererInterfaces[ + rendererID as any + ] as any as RendererInterface; let path: InspectElementParams['path'] = null; if (suspendedByPathIndex !== null && rendererPath !== null) { const suspendedByPathRendererIndex = @@ -709,14 +709,14 @@ export default class Agent extends EventEmitter<{ mergeRoots(inspectedScreen, inspectedRoots, suspendedByOffset); const dehydratedSuspendedBy: DehydratedData = inspectedRoots.suspendedBy; - const suspendedBy = ((dehydratedSuspendedBy.data: any): Array); + const suspendedBy = dehydratedSuspendedBy.data as any as Array; suspendedByOffset += suspendedBy.length; found = true; break; case 'no-change': found = true; const rootsSuspendedBy: Array = - (renderer.getElementAttributeByPath(id, ['suspendedBy']): any); + renderer.getElementAttributeByPath(id, ['suspendedBy']) as any; suspendedByOffset += rootsSuspendedBy.length; break; case 'not-found': @@ -792,9 +792,9 @@ export default class Agent extends EventEmitter<{ rendererID, suspendedSet, }) => { - const renderer = ((this._rendererInterfaces[ - (rendererID: any) - ]: any): RendererInterface); + const renderer = this._rendererInterfaces[ + rendererID as any + ] as any as RendererInterface; if (renderer.supportsTogglingSuspense) { renderer.overrideSuspenseMilestone(suspendedSet); } @@ -978,9 +978,9 @@ export default class Agent extends EventEmitter<{ setTraceUpdatesEnabled(traceUpdatesEnabled); for (const rendererID in this._rendererInterfaces) { - const renderer = ((this._rendererInterfaces[ - (rendererID: any) - ]: any): RendererInterface); + const renderer = this._rendererInterfaces[ + rendererID as any + ] as any as RendererInterface; renderer.setTraceUpdatesEnabled(traceUpdatesEnabled); } }; @@ -1004,9 +1004,9 @@ export default class Agent extends EventEmitter<{ }) => void = ({recordChangeDescriptions, recordTimeline}) => { this._isProfiling = true; for (const rendererID in this._rendererInterfaces) { - const renderer = ((this._rendererInterfaces[ - (rendererID: any) - ]: any): RendererInterface); + const renderer = this._rendererInterfaces[ + rendererID as any + ] as any as RendererInterface; renderer.startProfiling(recordChangeDescriptions, recordTimeline); } this._bridge.send('profilingStatus', this._isProfiling); @@ -1015,9 +1015,9 @@ export default class Agent extends EventEmitter<{ stopProfiling: () => void = () => { this._isProfiling = false; for (const rendererID in this._rendererInterfaces) { - const renderer = ((this._rendererInterfaces[ - (rendererID: any) - ]: any): RendererInterface); + const renderer = this._rendererInterfaces[ + rendererID as any + ] as any as RendererInterface; renderer.stopProfiling(); } this._bridge.send('profilingStatus', this._isProfiling); @@ -1060,9 +1060,9 @@ export default class Agent extends EventEmitter<{ componentFilters => { for (const rendererIDString in this._rendererInterfaces) { const rendererID = +rendererIDString; - const renderer = ((this._rendererInterfaces[ - (rendererID: any) - ]: any): RendererInterface); + const renderer = this._rendererInterfaces[ + rendererID as any + ] as any as RendererInterface; if (this._lastSelectedRendererID === rendererID) { // Changing component filters will unmount and remount the DevTools tree. // Track the last selection's path so we can restore the selection. @@ -1204,7 +1204,7 @@ export default class Agent extends EventEmitter<{ if (path !== null) { sessionStorageSetItem( SESSION_STORAGE_LAST_SELECTION_KEY, - JSON.stringify(({rendererID, path}: PersistedSelection)), + JSON.stringify({rendererID, path} as PersistedSelection), ); } else { sessionStorageRemoveItem(SESSION_STORAGE_LAST_SELECTION_KEY); diff --git a/packages/react-devtools-shared/src/backend/fiber/DevToolsFiberComponentStack.js b/packages/react-devtools-shared/src/backend/fiber/DevToolsFiberComponentStack.js index c938b6736323..4481b7865eed 100644 --- a/packages/react-devtools-shared/src/backend/fiber/DevToolsFiberComponentStack.js +++ b/packages/react-devtools-shared/src/backend/fiber/DevToolsFiberComponentStack.js @@ -165,7 +165,7 @@ export function getOwnerStackByFiberInDev( if (workInProgress.tag === HostText) { // Text nodes never have an owner/stack because they're not created through JSX. // We use the parent since text nodes are always created through a host parent. - workInProgress = (workInProgress.return: any); + workInProgress = workInProgress.return as any; } // The owner stack of the current fiber will be where it was created, i.e. inside its owner. @@ -197,7 +197,7 @@ export function getOwnerStackByFiberInDev( while (owner) { if (typeof owner.tag === 'number') { - const fiber: Fiber = (owner: any); + const fiber: Fiber = owner as any; owner = fiber._debugOwner; let debugStack: void | null | string | Error = fiber._debugStack; // If we don't actually print the stack if there is no owner of this JSX element. diff --git a/packages/react-devtools-shared/src/backend/fiber/renderer.js b/packages/react-devtools-shared/src/backend/fiber/renderer.js index bbc38d341a29..77adb8b4f564 100644 --- a/packages/react-devtools-shared/src/backend/fiber/renderer.js +++ b/packages/react-devtools-shared/src/backend/fiber/renderer.js @@ -215,7 +215,7 @@ function createFiberInstance(fiber: Fiber): FiberInstance { // This is used to represent a filtered Fiber but still lets us find its host instance. function createFilteredFiberInstance(fiber: Fiber): FilteredFiberInstance { - return ({ + return { kind: FILTERED_FIBER_INSTANCE, id: 0, parent: null, @@ -227,7 +227,7 @@ function createFilteredFiberInstance(fiber: Fiber): FilteredFiberInstance { suspendedBy: null, suspenseNode: null, data: fiber, - }: any); + } as any; } function createVirtualInstance( @@ -290,14 +290,14 @@ export function getDispatcherRef(renderer: { // We got a legacy dispatcher injected, let's create a wrapper proxy to translate. return { get H() { - return (injectedRef: any).current; + return (injectedRef as any).current; }, set H(value) { - (injectedRef: any).current = value; + (injectedRef as any).current = value; }, }; } - return (injectedRef: any); + return injectedRef as any; } // All environment names we've seen so far. This lets us create a list of filters to apply. @@ -971,7 +971,7 @@ export function attach( currentRoot = rootInstance; unmountInstanceRecursively(rootInstance); rootToFiberInstanceMap.delete(root); - currentRoot = (null: any); + currentRoot = null as any; }); if ( @@ -1040,7 +1040,7 @@ export function attach( currentRoot = newRoot; setRootPseudoKey(currentRoot.id, root.current); mountFiberRecursively(root.current, false); - currentRoot = (null: any); + currentRoot = null as any; }); // We need to write back the new ID for the focused Fiber. @@ -1278,7 +1278,7 @@ export function attach( } // When a mount or update is in progress, this value tracks the root that is being operated on. - let currentRoot: FiberInstance = (null: any); + let currentRoot: FiberInstance = null as any; // Removes a Fiber (and its alternate) from the Maps used to track their id. // This method should always be called when a Fiber is unmounting. @@ -2884,7 +2884,7 @@ export function attach( for (let i = 0; i < debugInfo.length; i++) { const debugEntry = debugInfo[i]; if (debugEntry.awaited) { - const asyncInfo: ReactAsyncInfo = (debugEntry: any); + const asyncInfo: ReactAsyncInfo = debugEntry as any; insertSuspendedBy(asyncInfo); } } @@ -2917,7 +2917,7 @@ export function attach( for (let j = 0; j < debugInfo.length; j++) { const debugEntry = debugInfo[j]; if (debugEntry.awaited) { - const asyncInfo: ReactAsyncInfo = (debugEntry: any); + const asyncInfo: ReactAsyncInfo = debugEntry as any; insertSuspendedBy(asyncInfo); } } @@ -2989,14 +2989,14 @@ export function attach( start = resourceEntry.startTime; end = start + resourceEntry.duration; // $FlowFixMe[prop-missing] - byteSize = (resourceEntry.transferSize: any) || 0; + byteSize = (resourceEntry.transferSize as any) || 0; } } } const value = instance.sheet; const promise = Promise.resolve(value); - (promise: any).status = 'fulfilled'; - (promise: any).value = value; + (promise as any).status = 'fulfilled'; + (promise as any).value = value; const ioInfo: ReactIOInfo = { name: 'stylesheet', start, @@ -3085,9 +3085,9 @@ export function attach( start = resourceEntry.startTime; end = start + resourceEntry.duration; // $FlowFixMe[prop-missing] - fileSize = (resourceEntry.decodedBodySize: any) || 0; + fileSize = (resourceEntry.decodedBodySize as any) || 0; // $FlowFixMe[prop-missing] - byteSize = (resourceEntry.transferSize: any) || 0; + byteSize = (resourceEntry.transferSize as any) || 0; } } } @@ -3111,8 +3111,8 @@ export function attach( value.fileSize = fileSize; } const promise = Promise.resolve(value); - (promise: any).status = 'fulfilled'; - (promise: any).value = value; + (promise as any).status = 'fulfilled'; + (promise as any).value = value; const ioInfo: ReactIOInfo = { name: 'img', start, @@ -3175,7 +3175,7 @@ export function attach( const debugEntry = fiber._debugInfo[i]; if (debugEntry.awaited) { // Async Info - const asyncInfo: ReactAsyncInfo = (debugEntry: any); + const asyncInfo: ReactAsyncInfo = debugEntry as any; if (level === virtualLevel) { // Track any async info between the previous virtual instance up until to this // instance and add it to the parent. This can add the same set multiple times @@ -3189,7 +3189,7 @@ export function attach( continue; } // Scan up until the next Component to see if this component changed environment. - const componentInfo: ReactComponentInfo = (debugEntry: any); + const componentInfo: ReactComponentInfo = debugEntry as any; const secondaryEnv = getSecondaryEnvironmentName(fiber._debugInfo, i); if (componentInfo.env != null) { knownEnvironmentNames.add(componentInfo.env); @@ -3789,7 +3789,7 @@ export function attach( // In some cases actualDuration might be 0 for fibers we worked on (particularly if we're using Date.now) // In other cases (e.g. Memo) actualDuration might be greater than 0 even if we "bailed out". const metadata = - ((currentCommitProfilingMetadata: any): CommitProfilingData); + currentCommitProfilingMetadata as any as CommitProfilingData; metadata.durations.push(id, actualDuration, selfDuration); metadata.maxActualDuration = Math.max( metadata.maxActualDuration, @@ -3819,7 +3819,7 @@ export function attach( (fiber.alternate !== null && updaters.has(fiber.alternate))) ) { const metadata = - ((currentCommitProfilingMetadata: any): CommitProfilingData); + currentCommitProfilingMetadata as any as CommitProfilingData; if (metadata.updaters === null) { metadata.updaters = []; } @@ -4044,7 +4044,7 @@ export function attach( const debugEntry = nextChild._debugInfo[i]; if (debugEntry.awaited) { // Async Info - const asyncInfo: ReactAsyncInfo = (debugEntry: any); + const asyncInfo: ReactAsyncInfo = debugEntry as any; if (level === virtualLevel) { // Track any async info between the previous virtual instance up until to this // instance and add it to the parent. This can add the same set multiple times @@ -4057,7 +4057,7 @@ export function attach( // Not a Component. Some other Debug Info. continue; } - const componentInfo: ReactComponentInfo = (debugEntry: any); + const componentInfo: ReactComponentInfo = debugEntry as any; const secondaryEnv = getSecondaryEnvironmentName( nextChild._debugInfo, i, @@ -4218,7 +4218,7 @@ export function attach( if (existingInstance !== null) { // Common case. Match in the same parent. const fiberInstance: FiberInstance | FilteredFiberInstance = - (existingInstance: any); // Only matches if it's a Fiber. + existingInstance as any; // Only matches if it's a Fiber. // We keep track if the order of the children matches the previous order. // They are always different referentially, but if the instances line up @@ -4235,7 +4235,7 @@ export function attach( updateFlags |= updateFiberRecursively( fiberInstance, nextChild, - (prevChild: any), + prevChild as any, traceNearestHostComponentUpdate, ); } else if (prevChild !== null && shouldFilterFiber(nextChild)) { @@ -5054,7 +5054,7 @@ export function attach( flushPendingEvents(currentRoot); - currentRoot = (null: any); + currentRoot = null as any; }); needsToFlushComponentLogs = false; @@ -5169,20 +5169,20 @@ export function attach( if (isProfiling && isProfilingSupported) { if (!shouldBailoutWithPendingOperations()) { - const commitProfilingMetadata = - ((rootToCommitProfilingMetadataMap: any): CommitProfilingMetadataMap).get( - currentRoot.id, - ); + const commitProfilingMetadata = ( + rootToCommitProfilingMetadataMap as any as CommitProfilingMetadataMap + ).get(currentRoot.id); if (commitProfilingMetadata != null) { commitProfilingMetadata.push( - ((currentCommitProfilingMetadata: any): CommitProfilingData), + currentCommitProfilingMetadata as any as CommitProfilingData, ); } else { - ((rootToCommitProfilingMetadataMap: any): CommitProfilingMetadataMap).set( - currentRoot.id, - [((currentCommitProfilingMetadata: any): CommitProfilingData)], - ); + ( + rootToCommitProfilingMetadataMap as any as CommitProfilingMetadataMap + ).set(currentRoot.id, [ + currentCommitProfilingMetadata as any as CommitProfilingData, + ]); } } } @@ -5196,7 +5196,7 @@ export function attach( hook.emit('traceUpdates', traceUpdatesForNodes); } - currentRoot = (null: any); + currentRoot = null as any; } function getResourceInstance(fiber: Fiber): HostInstance | null { @@ -5331,7 +5331,7 @@ export function attach( const owner = getUnfilteredOwner(fiber); if (owner != null) { if (typeof owner.tag === 'number') { - return getDisplayNameForFiber((owner: any)); + return getDisplayNameForFiber(owner as any); } else { return owner.name || ''; } @@ -5371,7 +5371,7 @@ export function attach( if (instance !== undefined) { if (instance.kind === FILTERED_FIBER_INSTANCE) { // A Filtered Fiber Instance will always have a Virtual Instance as a parent. - return ((instance.parent: any): VirtualInstance).id; + return (instance.parent as any as VirtualInstance).id; } return instance.id; } @@ -5406,7 +5406,7 @@ export function attach( ): mixed { if (isMostRecentlyInspectedElement(id)) { return getInObject( - ((mostRecentlyInspectedElement: any): InspectedElement), + mostRecentlyInspectedElement as any as InspectedElement, path, ); } @@ -5532,21 +5532,21 @@ export function attach( return null; } if (typeof owner.tag === 'number') { - const ownerFiber: Fiber = (owner: any); // Refined + const ownerFiber: Fiber = owner as any; // Refined owner = ownerFiber._debugOwner; } else { - const ownerInfo: ReactComponentInfo = (owner: any); // Refined + const ownerInfo: ReactComponentInfo = owner as any; // Refined owner = ownerInfo.owner; } while (owner) { if (typeof owner.tag === 'number') { - const ownerFiber: Fiber = (owner: any); // Refined + const ownerFiber: Fiber = owner as any; // Refined if (!shouldFilterFiber(ownerFiber)) { return ownerFiber; } owner = ownerFiber._debugOwner; } else { - const ownerInfo: ReactComponentInfo = (owner: any); // Refined + const ownerInfo: ReactComponentInfo = owner as any; // Refined if (!shouldFilterVirtual(ownerInfo, null)) { return ownerInfo; } @@ -5572,7 +5572,7 @@ export function attach( // isn't propagated down as the new owner. In that case we might match the alternate // instead. This is a bit hacky but the fastest check since type casting owner to a Fiber // needs a duck type check anyway. - parentInstance.data === (owner: any).alternate + parentInstance.data === (owner as any).alternate ) { if (parentInstance.kind === FILTERED_FIBER_INSTANCE) { return null; @@ -5653,7 +5653,7 @@ export function attach( } let firstInstance: null | DevToolsInstance = null; if (filterByChildInstance === null) { - firstInstance = (set.values().next().value: any); + firstInstance = set.values().next().value as any; } else { // eslint-disable-next-line no-for-of-loops/no-for-of-loops for (const childInstance of set.values()) { @@ -6089,7 +6089,7 @@ export function attach( ? inspectRootsRaw(devtoolsInstance.id) : inspectFiberInstanceRaw(devtoolsInstance); } - (devtoolsInstance: FilteredFiberInstance); // assert exhaustive + devtoolsInstance as FilteredFiberInstance; // assert exhaustive throw new Error('Unsupported instance kind'); } @@ -6170,7 +6170,7 @@ export function attach( context = consumerResolvedContext._currentValue || null; // Look for overridden value. - let current = ((fiber: any): Fiber).return; + let current = (fiber as any as Fiber).return; while (current !== null) { const currentType = current.type; const currentTypeSymbol = getTypeSymbol(currentType); @@ -6203,7 +6203,7 @@ export function attach( context = consumerResolvedContext._currentValue || null; // Look for overridden value. - let current = ((fiber: any): Fiber).return; + let current = (fiber as any as Fiber).return; while (current !== null) { const currentType = current.type; const currentTypeSymbol = getTypeSymbol(currentType); @@ -6703,7 +6703,7 @@ export function attach( ): void { if (isMostRecentlyInspectedElement(id)) { const value = getInObject( - ((mostRecentlyInspectedElement: any): InspectedElement), + mostRecentlyInspectedElement as any as InspectedElement, path, ); const key = `$reactTemp${count}`; @@ -6721,7 +6721,7 @@ export function attach( ): ?string { if (isMostRecentlyInspectedElement(id)) { const valueToCopy = getInObject( - ((mostRecentlyInspectedElement: any): InspectedElement), + mostRecentlyInspectedElement as any as InspectedElement, path, ); @@ -6756,7 +6756,7 @@ export function attach( path, value: cleanForBridge( getInObject( - ((mostRecentlyInspectedElement: any): InspectedElement), + mostRecentlyInspectedElement as any as InspectedElement, path, ), createIsPathAllowed(null, secondaryCategory), @@ -7071,7 +7071,7 @@ export function attach( break; case 'hooks': if (typeof overrideHookStateDeletePath === 'function') { - overrideHookStateDeletePath(fiber, ((hookID: any): number), path); + overrideHookStateDeletePath(fiber, hookID as any as number, path); } break; case 'props': @@ -7145,7 +7145,7 @@ export function attach( if (typeof overrideHookStateRenamePath === 'function') { overrideHookStateRenamePath( fiber, - ((hookID: any): number), + hookID as any as number, oldPath, newPath, ); @@ -7227,7 +7227,7 @@ export function attach( break; case 'hooks': if (typeof overrideHookState === 'function') { - overrideHookState(fiber, ((hookID: any): number), path, value); + overrideHookState(fiber, hookID as any as number, path, value); } break; case 'props': @@ -7445,13 +7445,16 @@ export function attach( ); } const rootID = rootInstance.id; - ((displayNamesByRootID: any): DisplayNamesByRootID).set( + (displayNamesByRootID as any as DisplayNamesByRootID).set( rootID, getDisplayNameForRoot(root.current), ); const initialTreeBaseDurations: Array<[number, number]> = []; snapshotTreeBaseDurations(rootInstance, initialTreeBaseDurations); - (initialTreeBaseDurationsMap: any).set(rootID, initialTreeBaseDurations); + (initialTreeBaseDurationsMap as any).set( + rootID, + initialTreeBaseDurations, + ); }); isProfiling = true; @@ -8113,7 +8116,7 @@ export function attach( // but it's at least somewhere within it. if (isError(unresolvedSource)) { return (instance.source = extractLocationFromOwnerStack( - (unresolvedSource: any), + unresolvedSource as any, )); } if (typeof unresolvedSource === 'string') { diff --git a/packages/react-devtools-shared/src/backend/fiber/shared/DevToolsFiberInspection.js b/packages/react-devtools-shared/src/backend/fiber/shared/DevToolsFiberInspection.js index 58c86f7cac09..c827753a78fb 100644 --- a/packages/react-devtools-shared/src/backend/fiber/shared/DevToolsFiberInspection.js +++ b/packages/react-devtools-shared/src/backend/fiber/shared/DevToolsFiberInspection.js @@ -21,7 +21,7 @@ export function isError(object: mixed): boolean { export function getFiberFlags(fiber: Fiber): number { // The name of this field changed from "effectTag" to "flags" - return fiber.flags !== undefined ? fiber.flags : (fiber: any).effectTag; + return fiber.flags !== undefined ? fiber.flags : (fiber as any).effectTag; } export function rootSupportsProfiling(root: any): boolean { @@ -61,7 +61,7 @@ export function getSecondaryEnvironmentName( index: number, ): null | string { if (debugInfo != null) { - const componentInfo: ReactComponentInfo = (debugInfo[index]: any); + const componentInfo: ReactComponentInfo = debugInfo[index] as any; for (let i = index + 1; i < debugInfo.length; i++) { const debugEntry = debugInfo[i]; if (typeof debugEntry.env === 'string') { diff --git a/packages/react-devtools-shared/src/backend/fiber/shared/DevToolsFiberInternalReactConstants.js b/packages/react-devtools-shared/src/backend/fiber/shared/DevToolsFiberInternalReactConstants.js index 053c519c887c..aa0449819f39 100644 --- a/packages/react-devtools-shared/src/backend/fiber/shared/DevToolsFiberInternalReactConstants.js +++ b/packages/react-devtools-shared/src/backend/fiber/shared/DevToolsFiberInternalReactConstants.js @@ -99,7 +99,7 @@ export function getInternalReactConstants(version: string): { const SuspenseyImagesMode = 0b0100000; - let ReactTypeOfWork: WorkTagMap = ((null: any): WorkTagMap); + let ReactTypeOfWork: WorkTagMap = null as any as WorkTagMap; // ********************************************************** // The section below is copied from files in React repo. diff --git a/packages/react-devtools-shared/src/backend/legacy/renderer.js b/packages/react-devtools-shared/src/backend/legacy/renderer.js index a908c727b182..07562065e712 100644 --- a/packages/react-devtools-shared/src/backend/legacy/renderer.js +++ b/packages/react-devtools-shared/src/backend/legacy/renderer.js @@ -146,7 +146,7 @@ export function attach( new WeakMap(); let getElementIDForHostInstance: GetElementIDForHostInstance = - ((null: any): GetElementIDForHostInstance); + null as any as GetElementIDForHostInstance; let findHostInstanceForInternalID: (id: number) => ?HostInstance; let getNearestMountedDOMNode = (node: Element): null | Element => { // Not implemented. @@ -198,7 +198,7 @@ export function attach( internalInstanceToIDMap.set(internalInstance, id); idToInternalInstanceMap.set(id, internalInstance); } - return ((internalInstanceToIDMap.get(internalInstance): any): number); + return internalInstanceToIDMap.get(internalInstance) as any as number; } function areEqualArrays(a: Array, b: Array) { @@ -832,7 +832,7 @@ export function attach( let owner = element._owner; if (owner) { - owners = ([]: Array); + owners = [] as Array; while (owner != null) { owners.push({ displayName: getData(owner).displayName || 'Unknown', diff --git a/packages/react-devtools-shared/src/backend/profilingHooks.js b/packages/react-devtools-shared/src/backend/profilingHooks.js index a3feb1748801..2a10eb5040f6 100644 --- a/packages/react-devtools-shared/src/backend/profilingHooks.js +++ b/packages/react-devtools-shared/src/backend/profilingHooks.js @@ -213,8 +213,8 @@ export function createProfilingHooks({ function markAndClear(markName: string) { // This method won't be called unless these functions are defined, so we can skip the extra typeof check. - ((performanceTarget: any): Performance).mark(markName); - ((performanceTarget: any): Performance).clearMarks(markName); + (performanceTarget as any as Performance).mark(markName); + (performanceTarget as any as Performance).clearMarks(markName); } function recordReactMeasureStarted( @@ -605,7 +605,7 @@ export function createProfilingHooks({ if (!wakeableIDs.has(wakeable)) { wakeableIDs.set(wakeable, wakeableID++); } - return ((wakeableIDs.get(wakeable): any): number); + return wakeableIDs.get(wakeable) as any as number; } function markComponentSuspended( @@ -626,7 +626,7 @@ export function createProfilingHooks({ // frameworks like Relay may also annotate Promises with a displayName, // describing what operation/data the thrown Promise is related to. // When this is available we should pass it along to the Timeline. - const displayName = (wakeable: any).displayName || ''; + const displayName = (wakeable as any).displayName || ''; let suspenseEvent: SuspenseEvent | null = null; // TODO (timeline) Record and cache component stack diff --git a/packages/react-devtools-shared/src/backend/shared/ReactSymbols.js b/packages/react-devtools-shared/src/backend/shared/ReactSymbols.js index 483671b90038..db5d05eb8da2 100644 --- a/packages/react-devtools-shared/src/backend/shared/ReactSymbols.js +++ b/packages/react-devtools-shared/src/backend/shared/ReactSymbols.js @@ -75,6 +75,6 @@ export const REACT_MEMO_CACHE_SENTINEL: symbol = Symbol.for( import type {ReactOptimisticKey} from 'shared/ReactTypes'; -export const REACT_OPTIMISTIC_KEY: ReactOptimisticKey = (Symbol.for( +export const REACT_OPTIMISTIC_KEY: ReactOptimisticKey = Symbol.for( 'react.optimistic_key', -): any); +) as any; diff --git a/packages/react-devtools-shared/src/backend/utils/index.js b/packages/react-devtools-shared/src/backend/utils/index.js index e9a8677000a0..816145fdb19d 100644 --- a/packages/react-devtools-shared/src/backend/utils/index.js +++ b/packages/react-devtools-shared/src/backend/utils/index.js @@ -61,7 +61,7 @@ export function copyWithDelete( const updated = isArray(obj) ? obj.slice() : {...obj}; if (index + 1 === path.length) { if (isArray(updated)) { - updated.splice(((key: any): number), 1); + updated.splice(key as any as number, 1); } else { delete updated[key]; } @@ -87,7 +87,7 @@ export function copyWithRename( // $FlowFixMe[incompatible-use] number or string is fine here updated[newKey] = updated[oldKey]; if (isArray(updated)) { - updated.splice(((oldKey: any): number), 1); + updated.splice(oldKey as any as number, 1); } else { delete updated[oldKey]; } diff --git a/packages/react-devtools-shared/src/backend/utils/parseStackTrace.js b/packages/react-devtools-shared/src/backend/utils/parseStackTrace.js index e18c2d7baa1b..109c12de37a9 100644 --- a/packages/react-devtools-shared/src/backend/utils/parseStackTrace.js +++ b/packages/react-devtools-shared/src/backend/utils/parseStackTrace.js @@ -224,12 +224,12 @@ function collectStackTrace( const enclosingLine: number = // $FlowFixMe[prop-missing] typeof callSite.getEnclosingLineNumber === 'function' - ? (callSite: any).getEnclosingLineNumber() || 0 + ? (callSite as any).getEnclosingLineNumber() || 0 : 0; const enclosingCol: number = // $FlowFixMe[prop-missing] typeof callSite.getEnclosingColumnNumber === 'function' - ? (callSite: any).getEnclosingColumnNumber() || 0 + ? (callSite as any).getEnclosingColumnNumber() || 0 : 0; const isAsync = // $FlowFixMe[prop-missing] diff --git a/packages/react-devtools-shared/src/backend/views/Highlighter/Highlighter.js b/packages/react-devtools-shared/src/backend/views/Highlighter/Highlighter.js index ddcb6f1ef11a..6fdd1ac7dc50 100644 --- a/packages/react-devtools-shared/src/backend/views/Highlighter/Highlighter.js +++ b/packages/react-devtools-shared/src/backend/views/Highlighter/Highlighter.js @@ -75,7 +75,7 @@ export function showOverlay( return isReactNativeEnvironment() ? showOverlayNative(elements, agent) : showOverlayWeb( - (elements: $ReadOnlyArray), + elements as $ReadOnlyArray, componentName, agent, hideAfterTimeout, diff --git a/packages/react-devtools-shared/src/backend/views/Highlighter/Overlay.js b/packages/react-devtools-shared/src/backend/views/Highlighter/Overlay.js index e55bdb4298c4..9384966b24d2 100644 --- a/packages/react-devtools-shared/src/backend/views/Highlighter/Overlay.js +++ b/packages/react-devtools-shared/src/backend/views/Highlighter/Overlay.js @@ -191,9 +191,9 @@ export default class Overlay { // We can't get the size of text nodes or comment nodes. React as of v15 // heavily uses comment nodes to delimit text. // TODO: We actually can measure text nodes. We should. - const elements: $ReadOnlyArray = (nodes.filter( + const elements: $ReadOnlyArray = nodes.filter( node => node.nodeType === Node.ELEMENT_NODE, - ): any); + ) as any; while (this.rects.length > elements.length) { const rect = this.rects.pop(); diff --git a/packages/react-devtools-shared/src/backend/views/Highlighter/index.js b/packages/react-devtools-shared/src/backend/views/Highlighter/index.js index 03397012b536..d0c6484b30b8 100644 --- a/packages/react-devtools-shared/src/backend/views/Highlighter/index.js +++ b/packages/react-devtools-shared/src/backend/views/Highlighter/index.js @@ -434,7 +434,7 @@ export default function setupHighlighter( lastHoveredNode = target; if (target.tagName === 'IFRAME') { - const iframe: HTMLIFrameElement = (target: any); + const iframe: HTMLIFrameElement = target as any; try { if (!iframesListeningTo.has(iframe)) { const window = iframe.contentWindow; @@ -493,9 +493,9 @@ export default function setupHighlighter( function getEventTarget(event: MouseEvent): HTMLElement { if (event.composed) { - return (event.composedPath()[0]: any); + return event.composedPath()[0] as any; } - return (event.target: any); + return event.target as any; } } diff --git a/packages/react-devtools-shared/src/backend/views/TraceUpdates/canvas.js b/packages/react-devtools-shared/src/backend/views/TraceUpdates/canvas.js index 6c7383183d06..56b6497d2d1b 100644 --- a/packages/react-devtools-shared/src/backend/views/TraceUpdates/canvas.js +++ b/packages/react-devtools-shared/src/backend/views/TraceUpdates/canvas.js @@ -48,7 +48,7 @@ function drawWeb(nodeToData: Map) { } const dpr = window.devicePixelRatio || 1; - const canvasFlow: HTMLCanvasElement = ((canvas: any): HTMLCanvasElement); + const canvasFlow: HTMLCanvasElement = canvas as any as HTMLCanvasElement; canvasFlow.width = window.innerWidth * dpr; canvasFlow.height = window.innerHeight * dpr; canvasFlow.style.width = `${window.innerWidth}px`; diff --git a/packages/react-devtools-shared/src/backend/views/TraceUpdates/index.js b/packages/react-devtools-shared/src/backend/views/TraceUpdates/index.js index 5b274e8a2f60..b7efe51337ab 100644 --- a/packages/react-devtools-shared/src/backend/views/TraceUpdates/index.js +++ b/packages/react-devtools-shared/src/backend/views/TraceUpdates/index.js @@ -47,7 +47,7 @@ export type Data = { const nodeToData: Map = new Map(); -let agent: Agent = ((null: any): Agent); +let agent: Agent = null as any as Agent; let drawAnimationFrameID: AnimationFrameID | null = null; let isEnabled: boolean = false; let redrawTimeoutID: TimeoutID | null = null; diff --git a/packages/react-devtools-shared/src/backendAPI.js b/packages/react-devtools-shared/src/backendAPI.js index c332393d2aa1..ae5641232971 100644 --- a/packages/react-devtools-shared/src/backendAPI.js +++ b/packages/react-devtools-shared/src/backendAPI.js @@ -204,7 +204,7 @@ function getPromiseForRequestID( const onInspectedElement = (data: any) => { if (data.responseID === requestID) { cleanup(); - resolve((data: T)); + resolve(data as T); } }; diff --git a/packages/react-devtools-shared/src/bridge.js b/packages/react-devtools-shared/src/bridge.js index 4ad87cceac4c..a568c22c392d 100644 --- a/packages/react-devtools-shared/src/bridge.js +++ b/packages/react-devtools-shared/src/bridge.js @@ -323,7 +323,7 @@ class Bridge< this._wallUnlisten = wall.listen((message: Message) => { if (message && message.event) { - (this: any).emit(message.event, message.payload); + (this as any).emit(message.event, message.payload); } }) || null; diff --git a/packages/react-devtools-shared/src/config/DevToolsFeatureFlags.core-fb.js b/packages/react-devtools-shared/src/config/DevToolsFeatureFlags.core-fb.js index 5d9c476b3bfd..684ca4d21cd0 100644 --- a/packages/react-devtools-shared/src/config/DevToolsFeatureFlags.core-fb.js +++ b/packages/react-devtools-shared/src/config/DevToolsFeatureFlags.core-fb.js @@ -27,4 +27,4 @@ import typeof * as FeatureFlagsType from './DevToolsFeatureFlags.default'; import typeof * as ExportsType from './DevToolsFeatureFlags.core-fb'; // Flow magic to verify the exports of this file match the original version. -((((null: any): ExportsType): FeatureFlagsType): ExportsType); +null as any as ExportsType as FeatureFlagsType as ExportsType; diff --git a/packages/react-devtools-shared/src/config/DevToolsFeatureFlags.core-oss.js b/packages/react-devtools-shared/src/config/DevToolsFeatureFlags.core-oss.js index 88b01afc3ee0..d506e05ad43f 100644 --- a/packages/react-devtools-shared/src/config/DevToolsFeatureFlags.core-oss.js +++ b/packages/react-devtools-shared/src/config/DevToolsFeatureFlags.core-oss.js @@ -27,4 +27,4 @@ import typeof * as FeatureFlagsType from './DevToolsFeatureFlags.default'; import typeof * as ExportsType from './DevToolsFeatureFlags.core-oss'; // Flow magic to verify the exports of this file match the original version. -((((null: any): ExportsType): FeatureFlagsType): ExportsType); +null as any as ExportsType as FeatureFlagsType as ExportsType; diff --git a/packages/react-devtools-shared/src/config/DevToolsFeatureFlags.extension-fb.js b/packages/react-devtools-shared/src/config/DevToolsFeatureFlags.extension-fb.js index 734e7988c858..2bf6eef6172e 100644 --- a/packages/react-devtools-shared/src/config/DevToolsFeatureFlags.extension-fb.js +++ b/packages/react-devtools-shared/src/config/DevToolsFeatureFlags.extension-fb.js @@ -27,4 +27,4 @@ import typeof * as FeatureFlagsType from './DevToolsFeatureFlags.default'; import typeof * as ExportsType from './DevToolsFeatureFlags.extension-fb'; // Flow magic to verify the exports of this file match the original version. -((((null: any): ExportsType): FeatureFlagsType): ExportsType); +null as any as ExportsType as FeatureFlagsType as ExportsType; diff --git a/packages/react-devtools-shared/src/config/DevToolsFeatureFlags.extension-oss.js b/packages/react-devtools-shared/src/config/DevToolsFeatureFlags.extension-oss.js index c9b665a9096e..dfafc3262ca4 100644 --- a/packages/react-devtools-shared/src/config/DevToolsFeatureFlags.extension-oss.js +++ b/packages/react-devtools-shared/src/config/DevToolsFeatureFlags.extension-oss.js @@ -27,4 +27,4 @@ import typeof * as FeatureFlagsType from './DevToolsFeatureFlags.default'; import typeof * as ExportsType from './DevToolsFeatureFlags.extension-oss'; // Flow magic to verify the exports of this file match the original version. -((((null: any): ExportsType): FeatureFlagsType): ExportsType); +null as any as ExportsType as FeatureFlagsType as ExportsType; diff --git a/packages/react-devtools-shared/src/devtools/ContextMenu/ContextMenu.js b/packages/react-devtools-shared/src/devtools/ContextMenu/ContextMenu.js index ded5bbb22e6c..5befb9ab57dd 100644 --- a/packages/react-devtools-shared/src/devtools/ContextMenu/ContextMenu.js +++ b/packages/react-devtools-shared/src/devtools/ContextMenu/ContextMenu.js @@ -84,10 +84,10 @@ export default function ContextMenu({ "Can't access context menu element. This is a bug in React DevTools.", ); } - const menu = (maybeMenu: HTMLDivElement); + const menu = maybeMenu as HTMLDivElement; function hideUnlessContains(event: Event) { - if (!menu.contains(((event.target: any): Node))) { + if (!menu.contains(event.target as any as Node)) { hide(); } } diff --git a/packages/react-devtools-shared/src/devtools/cache.js b/packages/react-devtools-shared/src/devtools/cache.js index c927b4d3dbf3..0473e38ee0a0 100644 --- a/packages/react-devtools-shared/src/devtools/cache.js +++ b/packages/react-devtools-shared/src/devtools/cache.js @@ -46,10 +46,10 @@ if (typeof React.use === 'function') { return React.use(Context); }; } else if ( - typeof (React: any).__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED === + typeof (React as any).__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED === 'object' ) { - const ReactCurrentDispatcher = (React: any) + const ReactCurrentDispatcher = (React as any) .__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher; readContext = function (Context: ReactContext) { const dispatcher = ReactCurrentDispatcher.current; @@ -79,9 +79,9 @@ const resourceConfigs: Map, Config> = new Map(); function getEntriesForResource( resource: any, ): Map | WeakMap { - let entriesForResource: Map | WeakMap = ((entries.get( + let entriesForResource: Map | WeakMap = entries.get( resource, - ): any): Map); + ) as any as Map; if (entriesForResource === undefined) { const config = resourceConfigs.get(resource); entriesForResource = @@ -103,12 +103,12 @@ function accessResult( const thenable = fetch(input); thenable.then( value => { - const fulfilledThenable: FulfilledThenable = (thenable: any); + const fulfilledThenable: FulfilledThenable = thenable as any; fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = value; }, error => { - const rejectedThenable: RejectedThenable = (thenable: any); + const rejectedThenable: RejectedThenable = thenable as any; rejectedThenable.status = 'rejected'; rejectedThenable.reason = error; }, @@ -171,9 +171,9 @@ export function createResource( write(key: Key, value: Value): void { const entriesForResource = getEntriesForResource(resource); - const fulfilledThenable: FulfilledThenable = (Promise.resolve( + const fulfilledThenable: FulfilledThenable = Promise.resolve( value, - ): any); + ) as any; fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = value; diff --git a/packages/react-devtools-shared/src/devtools/store.js b/packages/react-devtools-shared/src/devtools/store.js index 9fbb3beaab10..557020620e91 100644 --- a/packages/react-devtools-shared/src/devtools/store.js +++ b/packages/react-devtools-shared/src/devtools/store.js @@ -1313,7 +1313,7 @@ export default class Store extends EventEmitter<{ if (didMutate) { let weightAcrossRoots = 0; this._roots.forEach(rootID => { - const {weight} = ((this.getElementByID(rootID): any): Element); + const {weight} = this.getElementByID(rootID) as any as Element; weightAcrossRoots += weight; }); this._weightAcrossRoots = weightAcrossRoots; @@ -1426,7 +1426,7 @@ export default class Store extends EventEmitter<{ switch (operation) { case TREE_OPERATION_ADD: { const id = operations[i + 1]; - const type = ((operations[i + 2]: any): ElementType); + const type = operations[i + 2] as any as ElementType; i += 3; @@ -1820,7 +1820,7 @@ export default class Store extends EventEmitter<{ const parentID = operations[i + 2]; const nameStringID = operations[i + 3]; const isSuspended = operations[i + 4] === 1; - const numRects = ((operations[i + 5]: any): number); + const numRects = operations[i + 5] as any as number; let name = stringTable[nameStringID]; if (this._idToSuspense.has(id)) { @@ -2030,8 +2030,8 @@ export default class Store extends EventEmitter<{ break; } case SUSPENSE_TREE_OPERATION_RESIZE: { - const id = ((operations[i + 1]: any): number); - const numRects = ((operations[i + 2]: any): number); + const id = operations[i + 1] as any as number; + const numRects = operations[i + 2] as any as number; i += 3; const suspense = this._idToSuspense.get(id); @@ -2276,7 +2276,7 @@ export default class Store extends EventEmitter<{ if (didCollapse) { let weightAcrossRoots = 0; this._roots.forEach(rootID => { - const {weight} = ((this.getElementByID(rootID): any): Element); + const {weight} = this.getElementByID(rootID) as any as Element; weightAcrossRoots += weight; }); this._weightAcrossRoots = weightAcrossRoots; diff --git a/packages/react-devtools-shared/src/devtools/utils.js b/packages/react-devtools-shared/src/devtools/utils.js index 43d3ea6c837b..ba21ad0fe2b3 100644 --- a/packages/react-devtools-shared/src/devtools/utils.js +++ b/packages/react-devtools-shared/src/devtools/utils.js @@ -156,7 +156,7 @@ export function printStore( } store.roots.forEach(rootID => { - const {weight} = ((store.getElementByID(rootID): any): Element); + const {weight} = store.getElementByID(rootID) as any as Element; const maybeWeightLabel = includeWeight ? ` (${weight})` : ''; // Store does not (yet) expose a way to get errors/warnings per root. diff --git a/packages/react-devtools-shared/src/devtools/views/Components/Components.js b/packages/react-devtools-shared/src/devtools/views/Components/Components.js index 80b6d450331d..c1f14e6984ce 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/Components.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/Components.js @@ -239,4 +239,4 @@ function setResizeCSSVariable( } } -export default (portaledContent(Components): component()); +export default portaledContent(Components) as component(); diff --git a/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementContext.js b/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementContext.js index f6549fc243e4..922b564600a5 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementContext.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementContext.js @@ -57,7 +57,7 @@ type Context = { }; export const InspectedElementContext: ReactContext = - createContext(((null: any): Context)); + createContext(null as any as Context); export type Props = { children: ReactNodeList, diff --git a/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementContextTree.js b/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementContextTree.js index ac0b8a6a7739..129b3f76bf09 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementContextTree.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementContextTree.js @@ -81,7 +81,7 @@ export default function InspectedElementContextTree({ {isEmpty &&
None
} {/* $FlowFixMe[constant-condition] */} {!isEmpty && - (entries: any).map(([name, value]) => ( + (entries as any).map(([name, value]) => ( None} {/* $FlowFixMe[constant-condition] */} {!isEmpty && - (entries: any).map(([name, value]) => ( + (entries as any).map(([name, value]) => ( = createContext( - ((null: any): Context), + null as any as Context, ); NativeStyleContext.displayName = 'NativeStyleContext'; diff --git a/packages/react-devtools-shared/src/devtools/views/Components/OwnersListContext.js b/packages/react-devtools-shared/src/devtools/views/Components/OwnersListContext.js index 4044b93dc40a..9a89e3148820 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/OwnersListContext.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/OwnersListContext.js @@ -26,7 +26,7 @@ import type {Resource, Thenable} from '../../cache'; type Context = (id: number) => Array | null; const OwnersListContext: ReactContext = createContext( - ((null: any): Context), + null as any as Context, ); OwnersListContext.displayName = 'OwnersListContext'; @@ -52,7 +52,7 @@ const resource: Resource< | ResolveFn | (( result: Promise> | Array, - ) => void) = ((null: any): ResolveFn); + ) => void) = null as any as ResolveFn; const promise = new Promise(resolve => { resolveFn = resolve; }); @@ -60,7 +60,7 @@ const resource: Resource< // $FlowFixMe[incompatible-type] found when upgrading Flow inProgressRequests.set(element, {promise, resolveFn}); - return (promise: $FlowFixMe); + return promise as $FlowFixMe; }, (element: Element) => element, {useWeakMap: true}, @@ -88,7 +88,7 @@ function useChangeOwnerAction(): (nextOwnerID: number) => void { result: | Promise> | Array, - ) => void) = ((null: any): ResolveFn); + ) => void) = null as any as ResolveFn; const promise = new Promise(resolve => { resolveFn = resolve; }); diff --git a/packages/react-devtools-shared/src/devtools/views/Components/Tree.js b/packages/react-devtools-shared/src/devtools/views/Components/Tree.js index 5e79d0478bc5..be141e74a8cb 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/Tree.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/Tree.js @@ -215,7 +215,7 @@ export default function Tree(): React.Node { } const handleKeyDown = (event: KeyboardEvent) => { - if ((event: any).target.tagName === 'INPUT' || event.defaultPrevented) { + if ((event as any).target.tagName === 'INPUT' || event.defaultPrevented) { return; } diff --git a/packages/react-devtools-shared/src/devtools/views/Components/TreeContext.js b/packages/react-devtools-shared/src/devtools/views/Components/TreeContext.js index 58e86054d9ec..9ef558680fe1 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/TreeContext.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/TreeContext.js @@ -149,12 +149,12 @@ type Action = export type DispatcherContext = (action: Action) => void; const TreeStateContext: ReactContext = - createContext(((null: any): StateContext)); + createContext(null as any as StateContext); TreeStateContext.displayName = 'TreeStateContext'; // TODO: `dispatch` is an Action and should be named accordingly. const TreeDispatcherContext: ReactContext = - createContext(((null: any): DispatcherContext)); + createContext(null as any as DispatcherContext); TreeDispatcherContext.displayName = 'TreeDispatcherContext'; type State = { @@ -237,7 +237,7 @@ function reduceTreeState(store: Store, state: State, action: Action): State { case 'SELECT_ELEMENT_AT_INDEX': ownerSubtreeLeafElementID = null; - inspectedElementIndex = (action: ACTION_SELECT_ELEMENT_AT_INDEX) + inspectedElementIndex = (action as ACTION_SELECT_ELEMENT_AT_INDEX) .payload; break; case 'SELECT_ELEMENT_BY_ID': @@ -247,7 +247,7 @@ function reduceTreeState(store: Store, state: State, action: Action): State { // It might also cause problems if the specified element was inside of a (not yet expanded) subtree. lookupIDForIndex = false; - inspectedElementID = (action: ACTION_SELECT_ELEMENT_BY_ID).payload; + inspectedElementID = (action as ACTION_SELECT_ELEMENT_BY_ID).payload; inspectedElementIndex = inspectedElementID === null ? null @@ -270,7 +270,7 @@ function reduceTreeState(store: Store, state: State, action: Action): State { if (inspectedElementIndex !== null) { const selectedElement = store.getElementAtIndex( - ((inspectedElementIndex: any): number), + inspectedElementIndex as any as number, ); if (selectedElement !== null && selectedElement.parentID !== 0) { const parent = store.getElementByID(selectedElement.parentID); @@ -319,7 +319,7 @@ function reduceTreeState(store: Store, state: State, action: Action): State { } const selectedElement = store.getElementAtIndex( - ((inspectedElementIndex: any): number), + inspectedElementIndex as any as number, ); if (selectedElement !== null && selectedElement.ownerID !== 0) { const ownerIndex = store.getIndexOfElementID( @@ -336,7 +336,7 @@ function reduceTreeState(store: Store, state: State, action: Action): State { if (inspectedElementIndex !== null) { const selectedElement = store.getElementAtIndex( - ((inspectedElementIndex: any): number), + inspectedElementIndex as any as number, ); if (selectedElement !== null && selectedElement.parentID !== 0) { const parentIndex = store.getIndexOfElementID( @@ -362,7 +362,7 @@ function reduceTreeState(store: Store, state: State, action: Action): State { if (inspectedElementIndex !== null) { const selectedElement = store.getElementAtIndex( - ((inspectedElementIndex: any): number), + inspectedElementIndex as any as number, ); if (selectedElement !== null && selectedElement.parentID !== 0) { const parent = store.getElementByID(selectedElement.parentID); @@ -470,7 +470,7 @@ function reduceTreeState(store: Store, state: State, action: Action): State { inspectedElementID = null; } else { inspectedElementID = store.getElementIDAtIndex( - ((inspectedElementIndex: any): number), + inspectedElementIndex as any as number, ); } } @@ -520,15 +520,16 @@ function reduceSearchState(store: Store, state: State, action: Action): State { if (numPrevSearchResults > 0) { didRequestSearch = true; searchIndex = - ((searchIndex: any): number) > 0 - ? ((searchIndex: any): number) - 1 + (searchIndex as any as number) > 0 + ? (searchIndex as any as number) - 1 : numPrevSearchResults - 1; } break; case 'HANDLE_STORE_MUTATION': if (searchText !== '') { - const [addedElementIDs, removedElementIDs] = - (action: ACTION_HANDLE_STORE_MUTATION).payload; + const [addedElementIDs, removedElementIDs] = ( + action as ACTION_HANDLE_STORE_MUTATION + ).payload; removedElementIDs.forEach((parentID, id) => { // Prune this item from the search results. @@ -541,14 +542,16 @@ function reduceSearchState(store: Store, state: State, action: Action): State { // If the results are now empty, also deselect things. if (searchResults.length === 0) { searchIndex = null; - } else if (((searchIndex: any): number) >= searchResults.length) { + } else if ( + (searchIndex as any as number) >= searchResults.length + ) { searchIndex = searchResults.length - 1; } } }); addedElementIDs.forEach(id => { - const element = ((store.getElementByID(id): any): Element); + const element = store.getElementByID(id) as any as Element; // It's possible that multiple tree operations will fire before this action has run. // So it's important to check for elements that may have been added and then removed. @@ -559,16 +562,16 @@ function reduceSearchState(store: Store, state: State, action: Action): State { // Add this item to the search results if it matches. const regExp = createRegExp(searchText); if (displayName !== null && regExp.test(displayName)) { - const newElementIndex = ((store.getIndexOfElementID( + const newElementIndex = store.getIndexOfElementID( id, - ): any): number); + ) as any as number; let foundMatch = false; for (let index = 0; index < searchResults.length; index++) { const resultID = searchResults[index]; if ( newElementIndex < - ((store.getIndexOfElementID(resultID): any): number) + (store.getIndexOfElementID(resultID) as any as number) ) { foundMatch = true; searchResults = searchResults @@ -591,7 +594,7 @@ function reduceSearchState(store: Store, state: State, action: Action): State { case 'SET_SEARCH_TEXT': searchIndex = null; searchResults = []; - searchText = (action: ACTION_SET_SEARCH_TEXT).payload; + searchText = (action as ACTION_SET_SEARCH_TEXT).payload; if (searchText !== '') { const regExp = createRegExp(searchText); @@ -611,7 +614,7 @@ function reduceSearchState(store: Store, state: State, action: Action): State { } } else { searchIndex = Math.min( - ((prevSearchIndex: any): number), + prevSearchIndex as any as number, searchResults.length - 1, ); } @@ -638,9 +641,9 @@ function reduceSearchState(store: Store, state: State, action: Action): State { } } if (didRequestSearch && searchIndex !== null) { - inspectedElementID = ((searchResults[searchIndex]: any): number); + inspectedElementID = searchResults[searchIndex] as any as number; inspectedElementIndex = store.getIndexOfElementID( - ((inspectedElementID: any): number), + inspectedElementID as any as number, ); } @@ -706,13 +709,13 @@ function reduceOwnersState(store: Store, state: State, action: Action): State { break; case 'SELECT_ELEMENT_AT_INDEX': if (ownerFlatTree !== null) { - inspectedElementIndex = (action: ACTION_SELECT_ELEMENT_AT_INDEX) + inspectedElementIndex = (action as ACTION_SELECT_ELEMENT_AT_INDEX) .payload; } break; case 'SELECT_ELEMENT_BY_ID': if (ownerFlatTree !== null) { - const payload = (action: ACTION_SELECT_ELEMENT_BY_ID).payload; + const payload = (action as ACTION_SELECT_ELEMENT_BY_ID).payload; if (payload === null) { inspectedElementIndex = null; } else { @@ -752,7 +755,7 @@ function reduceOwnersState(store: Store, state: State, action: Action): State { // If the Store doesn't have any owners metadata, don't drill into an empty stack. // This is a confusing user experience. if (store.hasOwnerMetadata) { - ownerID = (action: ACTION_SELECT_OWNER).payload; + ownerID = (action as ACTION_SELECT_OWNER).payload; ownerFlatTree = store.getOwnersListForElement(ownerID); // Always force reset selection to be the top of the new owner tree. diff --git a/packages/react-devtools-shared/src/devtools/views/Components/ViewElementSourceContext.js b/packages/react-devtools-shared/src/devtools/views/Components/ViewElementSourceContext.js index 42f6b67723e8..9974c174fbac 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/ViewElementSourceContext.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/ViewElementSourceContext.js @@ -22,7 +22,7 @@ export type Context = { }; const ViewElementSourceContext: ReactContext = createContext( - ((null: any): Context), + null as any as Context, ); ViewElementSourceContext.displayName = 'ViewElementSourceContext'; diff --git a/packages/react-devtools-shared/src/devtools/views/DevTools.js b/packages/react-devtools-shared/src/devtools/views/DevTools.js index bf541f667287..1e36e43c9139 100644 --- a/packages/react-devtools-shared/src/devtools/views/DevTools.js +++ b/packages/react-devtools-shared/src/devtools/views/DevTools.js @@ -117,19 +117,19 @@ export type Props = { }; const componentsTab = { - id: ('components': TabID), + id: 'components' as TabID, icon: 'components', label: 'Components', title: 'React Components', }; const profilerTab = { - id: ('profiler': TabID), + id: 'profiler' as TabID, icon: 'profiler', label: 'Profiler', title: 'React Profiler', }; const suspenseTab = { - id: ('suspense': TabID), + id: 'suspense' as TabID, icon: 'suspense', label: 'Suspense', title: 'React Suspense', diff --git a/packages/react-devtools-shared/src/devtools/views/Editor/EditorPane.js b/packages/react-devtools-shared/src/devtools/views/Editor/EditorPane.js index 8237a59956d1..4930fab9a2e2 100644 --- a/packages/react-devtools-shared/src/devtools/views/Editor/EditorPane.js +++ b/packages/react-devtools-shared/src/devtools/views/Editor/EditorPane.js @@ -115,4 +115,4 @@ function EditorPane({selectedSource}: Props) { ); } -export default (portaledContent(EditorPane): component()); +export default portaledContent(EditorPane) as component(); diff --git a/packages/react-devtools-shared/src/devtools/views/ErrorBoundary/cache.js b/packages/react-devtools-shared/src/devtools/views/ErrorBoundary/cache.js index 6ae471ec993c..8ad55976582f 100644 --- a/packages/react-devtools-shared/src/devtools/views/ErrorBoundary/cache.js +++ b/packages/react-devtools-shared/src/devtools/views/ErrorBoundary/cache.js @@ -74,13 +74,13 @@ export function findGitHubIssue(errorMessage: string): GitHubIssue | null { }; const wake = () => { // This assumes they won't throw. - callbacks.forEach(callback => callback((thenable: any).value)); + callbacks.forEach(callback => callback((thenable as any).value)); callbacks.clear(); rejectCallbacks.clear(); }; const wakeRejections = () => { // This assumes they won't throw. - rejectCallbacks.forEach(callback => callback((thenable: any).reason)); + rejectCallbacks.forEach(callback => callback((thenable as any).reason)); rejectCallbacks.clear(); callbacks.clear(); }; @@ -96,20 +96,20 @@ export function findGitHubIssue(errorMessage: string): GitHubIssue | null { if (maybeItem) { const fulfilledThenable: FulfilledThenable = - (thenable: any); + thenable as any; fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = maybeItem; wake(); } else { const notFoundThenable: RejectedThenable = - (thenable: any); + thenable as any; notFoundThenable.status = 'rejected'; notFoundThenable.reason = null; wakeRejections(); } }) .catch(error => { - const rejectedThenable: RejectedThenable = (thenable: any); + const rejectedThenable: RejectedThenable = thenable as any; rejectedThenable.status = 'rejected'; rejectedThenable.reason = null; wakeRejections(); @@ -119,7 +119,7 @@ export function findGitHubIssue(errorMessage: string): GitHubIssue | null { setTimeout(() => { didTimeout = true; - const timedoutThenable: RejectedThenable = (thenable: any); + const timedoutThenable: RejectedThenable = thenable as any; timedoutThenable.status = 'rejected'; timedoutThenable.reason = null; wakeRejections(); diff --git a/packages/react-devtools-shared/src/devtools/views/InspectedElement/InspectedElementPane.js b/packages/react-devtools-shared/src/devtools/views/InspectedElement/InspectedElementPane.js index a47bffda8d7f..6abff0b01327 100644 --- a/packages/react-devtools-shared/src/devtools/views/InspectedElement/InspectedElementPane.js +++ b/packages/react-devtools-shared/src/devtools/views/InspectedElement/InspectedElementPane.js @@ -32,4 +32,4 @@ function InspectedElementPane() { ); } -export default (portaledContent(InspectedElementPane): component()); +export default portaledContent(InspectedElementPane) as component(); diff --git a/packages/react-devtools-shared/src/devtools/views/ModalDialog.js b/packages/react-devtools-shared/src/devtools/views/ModalDialog.js index a584d9a9e3d1..bb71e67e95f4 100644 --- a/packages/react-devtools-shared/src/devtools/views/ModalDialog.js +++ b/packages/react-devtools-shared/src/devtools/views/ModalDialog.js @@ -57,7 +57,7 @@ type ModalDialogContextType = { }; const ModalDialogContext: ReactContext = - createContext(((null: any): ModalDialogContextType)); + createContext(null as any as ModalDialogContextType); ModalDialogContext.displayName = 'ModalDialogContext'; function dialogReducer(state: State, action: Action) { diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitFlamegraph.js b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitFlamegraph.js index 3774a4d34004..4956516b8788 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitFlamegraph.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitFlamegraph.js @@ -57,13 +57,13 @@ export default function CommitFlamegraphAutoSizer(_: {}): React.Node { if (selectedCommitIndex !== null) { commitTree = profilingCache.getCommitTree({ commitIndex: selectedCommitIndex, - rootID: ((rootID: any): number), + rootID: rootID as any as number, }); chartData = profilingCache.getFlamegraphChartData({ commitIndex: selectedCommitIndex, commitTree, - rootID: ((rootID: any): number), + rootID: rootID as any as number, }); } @@ -75,8 +75,8 @@ export default function CommitFlamegraphAutoSizer(_: {}): React.Node { // Force Flow types to avoid checking for `null` here because there's no static proof that // by the time this render prop function is called, the values of the `let` variables have not changed. diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitFlamegraphListItem.js b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitFlamegraphListItem.js index 5bfe0a299f68..ac846b7be80d 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitFlamegraphListItem.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitFlamegraphListItem.js @@ -132,6 +132,6 @@ function CommitFlamegraphListItem({data, index, style}: Props): React.Node { ); } -export default (memo(CommitFlamegraphListItem, areEqual): component( +export default memo(CommitFlamegraphListItem, areEqual) as component( ...props: Props -)); +); diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitRanked.js b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitRanked.js index bc482776f4e8..57ed9983dd77 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitRanked.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitRanked.js @@ -57,13 +57,13 @@ export default function CommitRankedAutoSizer(_: {}): React.Node { if (selectedCommitIndex !== null) { commitTree = profilingCache.getCommitTree({ commitIndex: selectedCommitIndex, - rootID: ((rootID: any): number), + rootID: rootID as any as number, }); chartData = profilingCache.getRankedChartData({ commitIndex: selectedCommitIndex, commitTree, - rootID: ((rootID: any): number), + rootID: rootID as any as number, }); } @@ -73,8 +73,8 @@ export default function CommitRankedAutoSizer(_: {}): React.Node { {({height, width}) => ( diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitRankedListItem.js b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitRankedListItem.js index 707fddf6268c..99da9e9f0885 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitRankedListItem.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitRankedListItem.js @@ -79,6 +79,6 @@ function CommitRankedListItem({data, index, style}: Props) { ); } -export default (memo(CommitRankedListItem, areEqual): component( +export default memo(CommitRankedListItem, areEqual) as component( ...props: Props -)); +); diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitTreeBuilder.js b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitTreeBuilder.js index cdb50db8997d..d2b6eeb5d943 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitTreeBuilder.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitTreeBuilder.js @@ -63,9 +63,9 @@ export function getCommitTree({ rootToCommitTreeMap.set(rootID, []); } - const commitTrees = ((rootToCommitTreeMap.get( + const commitTrees = rootToCommitTreeMap.get( rootID, - ): any): Array); + ) as any as Array; if (commitIndex < commitTrees.length) { return commitTrees[commitIndex]; } @@ -87,7 +87,7 @@ export function getCommitTree({ ); } - let commitTree: CommitTree = ((null: any): CommitTree); + let commitTree: CommitTree = null as any as CommitTree; for (let index = commitTrees.length; index <= commitIndex; index++) { // Commits are generated sequentially and cached. // If this is the very first commit, start with the cached snapshot and apply the first mutation. @@ -140,9 +140,9 @@ function recursivelyInitializeTree( hocDisplayNames: node.hocDisplayNames, key: node.key, parentID, - treeBaseDuration: ((dataForRoot.initialTreeBaseDurations.get( + treeBaseDuration: dataForRoot.initialTreeBaseDurations.get( id, - ): any): number), + ) as any as number, type: node.type, compiledWithForget: node.compiledWithForget, }); @@ -175,7 +175,7 @@ function updateTree( }; let i = 2; - let id: number = ((null: any): number); + let id: number = null as any as number; // Reassemble the string table. const stringTable: Array = [ @@ -199,8 +199,8 @@ function updateTree( switch (operation) { case TREE_OPERATION_ADD: { - id = ((operations[i + 1]: any): number); - const type = ((operations[i + 2]: any): ElementType); + id = operations[i + 1] as any as number; + const type = operations[i + 2] as any as ElementType; i += 3; @@ -235,7 +235,7 @@ function updateTree( nodes.set(id, node); } else { - const parentID = ((operations[i]: any): number); + const parentID = operations[i] as any as number; i++; i++; // ownerID @@ -283,11 +283,11 @@ function updateTree( break; } case TREE_OPERATION_REMOVE: { - const removeLength = ((operations[i + 1]: any): number); + const removeLength = operations[i + 1] as any as number; i += 2; for (let removeIndex = 0; removeIndex < removeLength; removeIndex++) { - id = ((operations[i]: any): number); + id = operations[i] as any as number; i++; if (!nodes.has(id)) { @@ -319,12 +319,12 @@ function updateTree( break; } case TREE_OPERATION_REORDER_CHILDREN: { - id = ((operations[i + 1]: any): number); - const numChildren = ((operations[i + 2]: any): number); - const children = ((operations.slice( + id = operations[i + 1] as any as number; + const numChildren = operations[i + 2] as any as number; + const children = operations.slice( i + 3, i + 3 + numChildren, - ): any): Array); + ) as any as Array; i = i + 3 + numChildren; @@ -414,19 +414,19 @@ function updateTree( } case SUSPENSE_TREE_OPERATION_REMOVE: { - const removeLength = ((operations[i + 1]: any): number); + const removeLength = operations[i + 1] as any as number; i += 2 + removeLength; break; } case SUSPENSE_TREE_OPERATION_REORDER_CHILDREN: { - const suspenseID = ((operations[i + 1]: any): number); - const numChildren = ((operations[i + 2]: any): number); - const children = ((operations.slice( + const suspenseID = operations[i + 1] as any as number; + const numChildren = operations[i + 2] as any as number; + const children = operations.slice( i + 3, i + 3 + numChildren, - ): any): Array); + ) as any as Array; i = i + 3 + numChildren; @@ -442,18 +442,18 @@ function updateTree( } case SUSPENSE_TREE_OPERATION_RESIZE: { - const suspenseID = ((operations[i + 1]: any): number); - const numRects = ((operations[i + 2]: any): number); + const suspenseID = operations[i + 1] as any as number; + const numRects = operations[i + 2] as any as number; // $FlowFixMe[constant-condition] if (__DEBUG__) { if (numRects === -1) { debug('Suspense resize', `suspense ${suspenseID} rects null`); } else { - const rects = ((operations.slice( + const rects = operations.slice( i + 3, i + 3 + numRects * 4, - ): any): Array); + ) as any as Array; debug( 'Suspense resize', `suspense ${suspenseID} rects [${rects.join(',')}]`, @@ -468,7 +468,7 @@ function updateTree( case SUSPENSE_TREE_OPERATION_SUSPENDERS: { i++; - const changeLength = ((operations[i++]: any): number); + const changeLength = operations[i++] as any as number; for (let changeIndex = 0; changeIndex < changeLength; changeIndex++) { const suspenseNodeId = operations[i++]; diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/FlamegraphChartBuilder.js b/packages/react-devtools-shared/src/devtools/views/Profiler/FlamegraphChartBuilder.js index 53f9f4965779..f61806096388 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/FlamegraphChartBuilder.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/FlamegraphChartBuilder.js @@ -52,7 +52,7 @@ export function getChartData({ const chartDataKey = `${rootID}-${commitIndex}`; if (cachedChartData.has(chartDataKey)) { - return ((cachedChartData.get(chartDataKey): any): ChartData); + return cachedChartData.get(chartDataKey) as any as ChartData; } const idToDepthMap: Map = new Map(); diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/HoveredFiberInfo.js b/packages/react-devtools-shared/src/devtools/views/Profiler/HoveredFiberInfo.js index a6dfeffb3e20..097d2bd7d735 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/HoveredFiberInfo.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/HoveredFiberInfo.js @@ -57,7 +57,7 @@ export default function HoveredFiberInfo({fiberData}: Props): React.Node { const commitIndex = commitIndices[i]; if (selectedCommitIndex === commitIndex) { const {fiberActualDurations, fiberSelfDurations} = - profilerStore.getCommitData(((rootID: any): number), commitIndex); + profilerStore.getCommitData(rootID as any as number, commitIndex); const actualDuration = fiberActualDurations.get(id) || 0; const selfDuration = fiberSelfDurations.get(id) || 0; diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/Profiler.js b/packages/react-devtools-shared/src/devtools/views/Profiler/Profiler.js index 6254be06d832..e9511e091627 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/Profiler.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/Profiler.js @@ -243,4 +243,4 @@ const tabsWithTimeline = [ }, ]; -export default (portaledContent(Profiler): component()); +export default portaledContent(Profiler) as component(); diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/ProfilerContext.js b/packages/react-devtools-shared/src/devtools/views/Profiler/ProfilerContext.js index d593558dbdd1..07d82a54b48c 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/ProfilerContext.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/ProfilerContext.js @@ -83,7 +83,7 @@ export type Context = { }; const ProfilerContext: ReactContext = createContext( - ((null: any): Context), + null as any as Context, ); ProfilerContext.displayName = 'ProfilerContext'; @@ -228,12 +228,12 @@ function ProfilerContextController({children}: Props): React.Node { // Always check didRecordCommits before using commitData or filteredCommitIndices. const commitData = useMemo(() => { if (!didRecordCommits || rootID === null || profilingData === null) { - return ([]: Array); + return [] as Array; } const dataForRoot = profilingData.dataForRoots.get(rootID); return dataForRoot ? dataForRoot.commitData - : ([]: Array); + : ([] as Array); }, [didRecordCommits, rootID, profilingData]); // Commit filtering and navigation diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/ProfilingImportExportButtons.js b/packages/react-devtools-shared/src/devtools/views/Profiler/ProfilingImportExportButtons.js index 6bb3e229fbd1..920785bad653 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/ProfilingImportExportButtons.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/ProfilingImportExportButtons.js @@ -86,7 +86,7 @@ export default function ProfilingImportExportButtons(): React.Node { // TODO (profiling) Handle fileReader errors. const fileReader = new FileReader(); fileReader.addEventListener('load', () => { - const raw = ((fileReader.result: any): string); + const raw = fileReader.result as any as string; const json = JSON.parse(raw); if (!isArray(json) && hasOwnProperty.call(json, 'version')) { @@ -95,7 +95,7 @@ export default function ProfilingImportExportButtons(): React.Node { setFile(null); try { - const profilingDataExport = ((json: any): ProfilingDataExport); + const profilingDataExport = json as any as ProfilingDataExport; profilerStore.profilingData = prepareProfilingDataFrontendFromExport(profilingDataExport); } catch (error) { diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/RankedChartBuilder.js b/packages/react-devtools-shared/src/devtools/views/Profiler/RankedChartBuilder.js index 8cec8c6b924f..5cded846bc4c 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/RankedChartBuilder.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/RankedChartBuilder.js @@ -48,7 +48,7 @@ export function getChartData({ const chartDataKey = `${rootID}-${commitIndex}`; if (cachedChartData.has(chartDataKey)) { - return ((cachedChartData.get(chartDataKey): any): ChartData); + return cachedChartData.get(chartDataKey) as any as ChartData; } let maxSelfDuration = 0; diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/SidebarSelectedFiberInfo.js b/packages/react-devtools-shared/src/devtools/views/Profiler/SidebarSelectedFiberInfo.js index 430f302fbf0a..9781d3e8901d 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/SidebarSelectedFiberInfo.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/SidebarSelectedFiberInfo.js @@ -97,7 +97,7 @@ export default function SidebarSelectedFiberInfo(): React.Node { const commitIndex = commitIndices[i]; const {duration, timestamp} = profilerStore.getCommitData( - ((rootID: any): number), + rootID as any as number, commitIndex, ); @@ -136,7 +136,7 @@ export default function SidebarSelectedFiberInfo(): React.Node { compiledWithForget={node.compiledWithForget} /> )} - + {listItems.length > 0 && (
diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotCommitList.js b/packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotCommitList.js index 7b1cbcbdd261..356fa7e8b63a 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotCommitList.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotCommitList.js @@ -292,7 +292,11 @@ function List({ itemCount={filteredCommitIndices.length} itemData={itemData} itemSize={itemSize} - ref={(listRef: any) /* Flow bug? */} + ref={ + listRef as any + + /* Flow bug? */ + } width={width}> {SnapshotCommitListItem} diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotCommitListItem.js b/packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotCommitListItem.js index d9f80f005319..263f50849d22 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotCommitListItem.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotCommitListItem.js @@ -96,6 +96,6 @@ function SnapshotCommitListItem({data: itemData, index, style}: Props) { ); } -export default (memo(SnapshotCommitListItem, areEqual): component( +export default memo(SnapshotCommitListItem, areEqual) as component( ...props: Props -)); +); diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotSelector.js b/packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotSelector.js index 0d470ddb0003..6f1fa3ea43a9 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotSelector.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotSelector.js @@ -32,7 +32,7 @@ export default function SnapshotSelector(_: Props): React.Node { } = useContext(ProfilerContext); const {profilerStore} = useContext(StoreContext); - const {commitData} = profilerStore.getDataForRoot(((rootID: any): number)); + const {commitData} = profilerStore.getDataForRoot(rootID as any as number); const totalDurations: Array = []; const commitTimes: Array = []; diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/WhatChanged.js b/packages/react-devtools-shared/src/devtools/views/Profiler/WhatChanged.js index dffcd03350cd..e8fd79e969be 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/WhatChanged.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/WhatChanged.js @@ -37,7 +37,7 @@ export default function WhatChanged({ } const {changeDescriptions} = profilerStore.getCommitData( - ((rootID: any): number), + rootID as any as number, selectedCommitIndex, ); diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/useCommitFilteringAndNavigation.js b/packages/react-devtools-shared/src/devtools/views/Profiler/useCommitFilteringAndNavigation.js index d3369b4f9538..b1b685de25a2 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/useCommitFilteringAndNavigation.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/useCommitFilteringAndNavigation.js @@ -60,7 +60,7 @@ export function useCommitFilteringAndNavigation( reduced.push(index); } return reduced; - }, ([]: Array)); + }, [] as Array); }, [commitData], ); diff --git a/packages/react-devtools-shared/src/devtools/views/Settings/ComponentsSettings.js b/packages/react-devtools-shared/src/devtools/views/Settings/ComponentsSettings.js index 9b73e949429b..81df5b7c9722 100644 --- a/packages/react-devtools-shared/src/devtools/views/Settings/ComponentsSettings.js +++ b/packages/react-devtools-shared/src/devtools/views/Settings/ComponentsSettings.js @@ -281,7 +281,7 @@ export default function ComponentsSettings({ if (index >= 0) { if (componentFilter.type === ComponentFilterElementType) { cloned[index] = { - ...((cloned[index]: any): ElementTypeComponentFilter), + ...(cloned[index] as any as ElementTypeComponentFilter), isEnabled, }; } else if ( @@ -289,17 +289,17 @@ export default function ComponentsSettings({ componentFilter.type === ComponentFilterLocation ) { cloned[index] = { - ...((cloned[index]: any): RegExpComponentFilter), + ...(cloned[index] as any as RegExpComponentFilter), isEnabled, }; } else if (componentFilter.type === ComponentFilterHOC) { cloned[index] = { - ...((cloned[index]: any): BooleanComponentFilter), + ...(cloned[index] as any as BooleanComponentFilter), isEnabled, }; } else if (componentFilter.type === ComponentFilterEnvironmentName) { cloned[index] = { - ...((cloned[index]: any): EnvironmentNameComponentFilter), + ...(cloned[index] as any as EnvironmentNameComponentFilter), isEnabled, }; } @@ -404,10 +404,10 @@ export default function ComponentsSettings({ onChange={({currentTarget}) => changeFilterType( componentFilter, - ((parseInt( + parseInt( currentTarget.value, 10, - ): any): ComponentFilterType), + ) as any as ComponentFilterType, ) }> {/* TODO: currently disabled, need find a new way of doing this @@ -445,7 +445,7 @@ export default function ComponentsSettings({ onChange={({currentTarget}) => updateFilterValueElementType( componentFilter, - ((parseInt(currentTarget.value, 10): any): ElementType), + parseInt(currentTarget.value, 10) as any as ElementType, ) }> {isInternalFacebookBuild && ( diff --git a/packages/react-devtools-shared/src/devtools/views/Settings/SettingsContext.js b/packages/react-devtools-shared/src/devtools/views/Settings/SettingsContext.js index c20249e89942..27bd47c349da 100644 --- a/packages/react-devtools-shared/src/devtools/views/Settings/SettingsContext.js +++ b/packages/react-devtools-shared/src/devtools/views/Settings/SettingsContext.js @@ -56,7 +56,7 @@ type Context = { }; const SettingsContext: ReactContext = createContext( - ((null: any): Context), + null as any as Context, ); SettingsContext.displayName = 'SettingsContext'; @@ -116,24 +116,24 @@ function SettingsContextController({ const documentElements = useMemo(() => { const array: Array = [ - ((document.documentElement: any): HTMLElement), + document.documentElement as any as HTMLElement, ]; if (componentsPortalContainer != null) { array.push( - ((componentsPortalContainer.ownerDocument - .documentElement: any): HTMLElement), + componentsPortalContainer.ownerDocument + .documentElement as any as HTMLElement, ); } if (profilerPortalContainer != null) { array.push( - ((profilerPortalContainer.ownerDocument - .documentElement: any): HTMLElement), + profilerPortalContainer.ownerDocument + .documentElement as any as HTMLElement, ); } if (suspensePortalContainer != null) { array.push( - ((suspensePortalContainer.ownerDocument - .documentElement: any): HTMLElement), + suspensePortalContainer.ownerDocument + .documentElement as any as HTMLElement, ); } return array; @@ -218,11 +218,11 @@ export function updateDisplayDensity( ): void { // Sizes and paddings/margins are all rem-based, // so update the root font-size as well when the display preference changes. - const computedStyle = getComputedStyle((document.body: any)); + const computedStyle = getComputedStyle(document.body as any); const fontSize = computedStyle.getPropertyValue( `--${displayDensity}-root-font-size`, ); - const root = ((document.querySelector(':root'): any): HTMLElement); + const root = document.querySelector(':root') as any as HTMLElement; root.style.fontSize = fontSize; } diff --git a/packages/react-devtools-shared/src/devtools/views/Settings/SettingsModalContext.js b/packages/react-devtools-shared/src/devtools/views/Settings/SettingsModalContext.js index f8f76053fc12..4ba7dd20139f 100644 --- a/packages/react-devtools-shared/src/devtools/views/Settings/SettingsModalContext.js +++ b/packages/react-devtools-shared/src/devtools/views/Settings/SettingsModalContext.js @@ -34,7 +34,7 @@ type Context = { }; const SettingsModalContext: ReactContext = createContext( - ((null: any): Context), + null as any as Context, ); SettingsModalContext.displayName = 'SettingsModalContext'; diff --git a/packages/react-devtools-shared/src/devtools/views/SuspenseTab/SuspenseRects.js b/packages/react-devtools-shared/src/devtools/views/SuspenseTab/SuspenseRects.js index a1a9f85411ce..b61ba892c33d 100644 --- a/packages/react-devtools-shared/src/devtools/views/SuspenseTab/SuspenseRects.js +++ b/packages/react-devtools-shared/src/devtools/views/SuspenseTab/SuspenseRects.js @@ -451,7 +451,7 @@ function SuspenseRectsTransition({id}: {id: Element['id']}): React$Node { }); } -const ViewBox = createContext((null: any)); +const ViewBox = createContext(null as any); function SuspenseRectsContainer({ scaleRef, diff --git a/packages/react-devtools-shared/src/devtools/views/SuspenseTab/SuspenseTab.js b/packages/react-devtools-shared/src/devtools/views/SuspenseTab/SuspenseTab.js index 3fdd9fe935a3..d59a037d38c9 100644 --- a/packages/react-devtools-shared/src/devtools/views/SuspenseTab/SuspenseTab.js +++ b/packages/react-devtools-shared/src/devtools/views/SuspenseTab/SuspenseTab.js @@ -645,4 +645,4 @@ function setResizeCSSVariable( } } -export default (portaledContent(SuspenseTab): component()); +export default portaledContent(SuspenseTab) as component(); diff --git a/packages/react-devtools-shared/src/devtools/views/SuspenseTab/SuspenseTreeContext.js b/packages/react-devtools-shared/src/devtools/views/SuspenseTab/SuspenseTreeContext.js index 4e07336b79f7..68dc5adb606e 100644 --- a/packages/react-devtools-shared/src/devtools/views/SuspenseTab/SuspenseTreeContext.js +++ b/packages/react-devtools-shared/src/devtools/views/SuspenseTab/SuspenseTreeContext.js @@ -97,11 +97,11 @@ export type SuspenseTreeAction = export type SuspenseTreeDispatch = (action: SuspenseTreeAction) => void; const SuspenseTreeStateContext: ReactContext = - createContext(((null: any): SuspenseTreeState)); + createContext(null as any as SuspenseTreeState); SuspenseTreeStateContext.displayName = 'SuspenseTreeStateContext'; const SuspenseTreeDispatcherContext: ReactContext = - createContext(((null: any): SuspenseTreeDispatch)); + createContext(null as any as SuspenseTreeDispatch); SuspenseTreeDispatcherContext.displayName = 'SuspenseTreeDispatcherContext'; type Props = { diff --git a/packages/react-devtools-shared/src/devtools/views/TabBar.js b/packages/react-devtools-shared/src/devtools/views/TabBar.js index a277082ab264..4575c0ae8942 100644 --- a/packages/react-devtools-shared/src/devtools/views/TabBar.js +++ b/packages/react-devtools-shared/src/devtools/views/TabBar.js @@ -41,7 +41,7 @@ export default function TabBar({ type, }: Props): React.Node { if (!tabs.some(tab => tab !== null && tab.id === currentTab)) { - const firstTab = ((tabs.find(tab => tab !== null): any): TabInfo); + const firstTab = tabs.find(tab => tab !== null) as any as TabInfo; selectTab(firstTab.id); } diff --git a/packages/react-devtools-shared/src/devtools/views/context.js b/packages/react-devtools-shared/src/devtools/views/context.js index e04d3433c093..d2ff088c362e 100644 --- a/packages/react-devtools-shared/src/devtools/views/context.js +++ b/packages/react-devtools-shared/src/devtools/views/context.js @@ -15,11 +15,11 @@ import type {ViewAttributeSource} from 'react-devtools-shared/src/devtools/views import type {FrontendBridge} from 'react-devtools-shared/src/bridge'; export const BridgeContext: ReactContext = - createContext(((null: any): FrontendBridge)); + createContext(null as any as FrontendBridge); BridgeContext.displayName = 'BridgeContext'; export const StoreContext: ReactContext = createContext( - ((null: any): Store), + null as any as Store, ); StoreContext.displayName = 'StoreContext'; diff --git a/packages/react-devtools-shared/src/devtools/views/hooks.js b/packages/react-devtools-shared/src/devtools/views/hooks.js index 8589ea15d016..a861b3201f64 100644 --- a/packages/react-devtools-shared/src/devtools/views/hooks.js +++ b/packages/react-devtools-shared/src/devtools/views/hooks.js @@ -165,7 +165,7 @@ export function useLocalStorage( console.log(error); } if (typeof initialValue === 'function') { - return ((initialValue: any): () => T)(); + return (initialValue as any as () => T)(); } else { return initialValue; } @@ -188,7 +188,7 @@ export function useLocalStorage( (value: $FlowFixMe) => { try { const valueToStore = - value instanceof Function ? (value: any)(storedValue) : value; + value instanceof Function ? (value as any)(storedValue) : value; localStorageSetItem(key, JSON.stringify(valueToStore)); // Notify listeners that this setting has changed. diff --git a/packages/react-devtools-shared/src/devtools/views/utils.js b/packages/react-devtools-shared/src/devtools/views/utils.js index a2d254bc27d8..6fefc2fff1db 100644 --- a/packages/react-devtools-shared/src/devtools/views/utils.js +++ b/packages/react-devtools-shared/src/devtools/views/utils.js @@ -134,7 +134,7 @@ export function serializeDataForCopy(props: Object): string { export function serializeHooksForCopy(hooks: HooksTree | null): string { // $FlowFixMe[not-an-object] "HooksTree is not an object" - const cloned = Object.assign(([]: Array), hooks); + const cloned = Object.assign([] as Array, hooks); const queue = [...cloned]; diff --git a/packages/react-devtools-shared/src/dynamicImportCache.js b/packages/react-devtools-shared/src/dynamicImportCache.js index 726352cc933d..aa4add28b58b 100644 --- a/packages/react-devtools-shared/src/dynamicImportCache.js +++ b/packages/react-devtools-shared/src/dynamicImportCache.js @@ -93,7 +93,7 @@ export function loadModule(moduleLoaderFunction: ModuleLoaderFunction): Module { } // This assumes they won't throw. - rejectCallbacks.forEach(callback => callback((thenable: any).reason)); + rejectCallbacks.forEach(callback => callback((thenable as any).reason)); rejectCallbacks.clear(); callbacks.clear(); }; @@ -115,7 +115,7 @@ export function loadModule(moduleLoaderFunction: ModuleLoaderFunction): Module { return; } - const fulfilledThenable: FulfilledThenable = (thenable: any); + const fulfilledThenable: FulfilledThenable = thenable as any; fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = module; @@ -135,7 +135,7 @@ export function loadModule(moduleLoaderFunction: ModuleLoaderFunction): Module { console.log(error); - const rejectedThenable: RejectedThenable = (thenable: any); + const rejectedThenable: RejectedThenable = thenable as any; rejectedThenable.status = 'rejected'; rejectedThenable.reason = error; @@ -156,7 +156,7 @@ export function loadModule(moduleLoaderFunction: ModuleLoaderFunction): Module { didTimeout = true; - const rejectedThenable: RejectedThenable = (thenable: any); + const rejectedThenable: RejectedThenable = thenable as any; rejectedThenable.status = 'rejected'; rejectedThenable.reason = null; diff --git a/packages/react-devtools-shared/src/hook.js b/packages/react-devtools-shared/src/hook.js index f8778e584b87..5ec953101aa0 100644 --- a/packages/react-devtools-shared/src/hook.js +++ b/packages/react-devtools-shared/src/hook.js @@ -493,7 +493,7 @@ export function installHook( // The backend is what implements a message queue, so it's the only one that injects onErrorOrWarning. if (onErrorOrWarning != null) { onErrorOrWarning( - ((method: any): 'error' | 'warn'), + method as any as 'error' | 'warn', args.slice(), ); } @@ -699,19 +699,15 @@ export function installHook( }); } - Object.defineProperty( - target, - '__REACT_DEVTOOLS_GLOBAL_HOOK__', - ({ - // This property needs to be configurable for the test environment, - // else we won't be able to delete and recreate it between tests. - configurable: __DEV__, - enumerable: false, - get() { - return hook; - }, - }: Object), - ); + Object.defineProperty(target, '__REACT_DEVTOOLS_GLOBAL_HOOK__', { + // This property needs to be configurable for the test environment, + // else we won't be able to delete and recreate it between tests. + configurable: __DEV__, + enumerable: false, + get() { + return hook; + }, + } as Object); return hook; } diff --git a/packages/react-devtools-shared/src/hookNamesCache.js b/packages/react-devtools-shared/src/hookNamesCache.js index 0e3a043be17a..7123318cfb34 100644 --- a/packages/react-devtools-shared/src/hookNamesCache.js +++ b/packages/react-devtools-shared/src/hookNamesCache.js @@ -115,7 +115,7 @@ export function loadHookNames( } // This assumes they won't throw. - callbacks.forEach(callback => callback((thenable: any).value)); + callbacks.forEach(callback => callback((thenable as any).value)); callbacks.clear(); rejectCallbacks.clear(); }; @@ -125,7 +125,7 @@ export function loadHookNames( timeoutID = null; } // This assumes they won't throw. - rejectCallbacks.forEach(callback => callback((thenable: any).reason)); + rejectCallbacks.forEach(callback => callback((thenable as any).reason)); rejectCallbacks.clear(); callbacks.clear(); }; @@ -159,7 +159,7 @@ export function loadHookNames( if (hookNames) { const fulfilledThenable: FulfilledThenable = - (thenable: any); + thenable as any; fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = hookNames; status = 'success'; @@ -168,7 +168,7 @@ export function loadHookNames( wake(); } else { const notFoundThenable: RejectedThenable = - (thenable: any); + thenable as any; notFoundThenable.status = 'rejected'; notFoundThenable.reason = null; status = 'error'; @@ -190,7 +190,7 @@ export function loadHookNames( console.error(error); const rejectedThenable: RejectedThenable = - (thenable: any); + thenable as any; rejectedThenable.status = 'rejected'; rejectedThenable.reason = null; @@ -211,7 +211,7 @@ export function loadHookNames( didTimeout = true; - const timedoutThenable: RejectedThenable = (thenable: any); + const timedoutThenable: RejectedThenable = thenable as any; timedoutThenable.status = 'rejected'; timedoutThenable.reason = null; diff --git a/packages/react-devtools-shared/src/hooks/SourceMapConsumer.js b/packages/react-devtools-shared/src/hooks/SourceMapConsumer.js index 468905bf8716..a18ad15b50ec 100644 --- a/packages/react-devtools-shared/src/hooks/SourceMapConsumer.js +++ b/packages/react-devtools-shared/src/hooks/SourceMapConsumer.js @@ -39,9 +39,9 @@ export default function SourceMapConsumer( sourceMapJSON: MixedSourceMap | IndexSourceMapSection, ): SourceMapConsumerType { if (sourceMapJSON.sections != null) { - return IndexedSourceMapConsumer(((sourceMapJSON: any): IndexSourceMap)); + return IndexedSourceMapConsumer(sourceMapJSON as any as IndexSourceMap); } else { - return BasicSourceMapConsumer(((sourceMapJSON: any): BasicSourceMap)); + return BasicSourceMapConsumer(sourceMapJSON as any as BasicSourceMap); } } @@ -124,15 +124,15 @@ function BasicSourceMapConsumer(sourceMapJSON: BasicSourceMap) { return { column, line, - sourceContent: ((sourceContent: any): string | null), - sourceURL: ((sourceURL: any): string | null), + sourceContent: sourceContent as any as string | null, + sourceURL: sourceURL as any as string | null, ignored, }; } - return (({ + return { originalPositionFor, - }: any): SourceMapConsumerType); + } as any as SourceMapConsumerType; } type Section = { @@ -231,7 +231,7 @@ function IndexedSourceMapConsumer(sourceMapJSON: IndexSourceMap) { }); } - return (({ + return { originalPositionFor, - }: any): SourceMapConsumerType); + } as any as SourceMapConsumerType; } diff --git a/packages/react-devtools-shared/src/hooks/parseHookNames/loadSourceAndMetadata.js b/packages/react-devtools-shared/src/hooks/parseHookNames/loadSourceAndMetadata.js index fa4235dc2c2d..3bfc83dd2547 100644 --- a/packages/react-devtools-shared/src/hooks/parseHookNames/loadSourceAndMetadata.js +++ b/packages/react-devtools-shared/src/hooks/parseHookNames/loadSourceAndMetadata.js @@ -141,7 +141,7 @@ function extractAndLoadSourceMapJSON( locationKeyToHookSourceAndMetadata.forEach(hookSourceAndMetadata => { const sourceMapRegex = / ?sourceMappingURL=([^\s'"]+)/gm; const runtimeSourceCode = - ((hookSourceAndMetadata.runtimeSourceCode: any): string); + hookSourceAndMetadata.runtimeSourceCode as any as string; // TODO (named hooks) Search for our custom metadata first. // If it's found, we should use it rather than source maps. @@ -175,9 +175,11 @@ function extractAndLoadSourceMapJSON( // Web apps like Code Sandbox embed multiple inline source maps. // In this case, we need to loop through and find the right one. // We may also need to trim any part of this string that isn't based64 encoded data. - const trimmed = ((sourceMappingURL.match( - /base64,([a-zA-Z0-9+\/=]+)/, - ): any): Array)[1]; + const trimmed = ( + sourceMappingURL.match( + /base64,([a-zA-Z0-9+\/=]+)/, + ) as any as Array + )[1]; const decoded = withSyncPerfMeasurements( 'decodeBase64String()', () => decodeBase64String(trimmed), @@ -431,7 +433,7 @@ function initializeHookSourceAndMetadata( const locationKey = getHookSourceLocationKey(hookSource); if (!locationKeyToHookSourceAndMetadata.has(locationKey)) { // Can't be null because getHookSourceLocationKey() would have thrown - const runtimeSourceURL = ((hookSource.fileName: any): string); + const runtimeSourceURL = hookSource.fileName as any as string; const hookSourceAndMetadata: HookSourceAndMetadata = { hookSource, @@ -477,7 +479,7 @@ function loadSourceFiles( return withAsyncPerfMeasurements( `fetchFileWithCaching("${url}")`, () => { - return ((fetchFileWithCaching: any): FetchFileWithCaching)(url); + return (fetchFileWithCaching as any as FetchFileWithCaching)(url); }, ); }; diff --git a/packages/react-devtools-shared/src/hooks/parseHookNames/parseSourceAndMetadata.js b/packages/react-devtools-shared/src/hooks/parseHookNames/parseSourceAndMetadata.js index 14ab77896726..4e01d6b360a9 100644 --- a/packages/react-devtools-shared/src/hooks/parseHookNames/parseSourceAndMetadata.js +++ b/packages/react-devtools-shared/src/hooks/parseHookNames/parseSourceAndMetadata.js @@ -129,7 +129,7 @@ function findHookNames( hooksList.map(hook => { // We already guard against a null HookSource in parseHookNames() - const hookSource = ((hook.hookSource: any): HookSource); + const hookSource = hook.hookSource as any as HookSource; const fileName = hookSource.fileName; if (!fileName) { return null; // Should not be reachable. @@ -177,8 +177,8 @@ function findHookNames( getHookName( hook, hookParsedMetadata.originalSourceAST, - ((hookParsedMetadata.originalSourceCode: any): string), - ((originalSourceLineNumber: any): number), + hookParsedMetadata.originalSourceCode as any as string, + originalSourceLineNumber as any as number, originalSourceColumnNumber, ), ); @@ -255,7 +255,7 @@ function parseSourceAST( const {metadataConsumer, sourceMapConsumer} = hookParsedMetadata; const runtimeSourceCode = - ((hookSourceAndMetadata.runtimeSourceCode: any): string); + hookSourceAndMetadata.runtimeSourceCode as any as string; let hasHookMap = false; let originalSourceURL; let originalSourceCode; diff --git a/packages/react-devtools-shared/src/hydration.js b/packages/react-devtools-shared/src/hydration.js index 3670514ff4c6..d11c6220d4c5 100644 --- a/packages/react-devtools-shared/src/hydration.js +++ b/packages/react-devtools-shared/src/hydration.js @@ -26,15 +26,15 @@ import type { import noop from 'shared/noop'; export const meta = { - inspectable: (Symbol('inspectable'): symbol), - inspected: (Symbol('inspected'): symbol), - name: (Symbol('name'): symbol), - preview_long: (Symbol('preview_long'): symbol), - preview_short: (Symbol('preview_short'): symbol), - readonly: (Symbol('readonly'): symbol), - size: (Symbol('size'): symbol), - type: (Symbol('type'): symbol), - unserializable: (Symbol('unserializable'): symbol), + inspectable: Symbol('inspectable') as symbol, + inspected: Symbol('inspected') as symbol, + name: Symbol('name') as symbol, + preview_long: Symbol('preview_long') as symbol, + preview_short: Symbol('preview_short') as symbol, + readonly: Symbol('readonly') as symbol, + size: Symbol('size') as symbol, + type: Symbol('type') as symbol, + unserializable: Symbol('unserializable') as symbol, }; export type Dehydrated = { diff --git a/packages/react-devtools-shared/src/inspectedElementCache.js b/packages/react-devtools-shared/src/inspectedElementCache.js index 820baf3380dd..8a51e2543a9f 100644 --- a/packages/react-devtools-shared/src/inspectedElementCache.js +++ b/packages/react-devtools-shared/src/inspectedElementCache.js @@ -101,13 +101,13 @@ export function inspectElement( const wake = () => { // This assumes they won't throw. - callbacks.forEach(callback => callback((thenable: any).value)); + callbacks.forEach(callback => callback((thenable as any).value)); callbacks.clear(); rejectCallbacks.clear(); }; const wakeRejections = () => { // This assumes they won't throw. - rejectCallbacks.forEach(callback => callback((thenable: any).reason)); + rejectCallbacks.forEach(callback => callback((thenable as any).reason)); rejectCallbacks.clear(); callbacks.clear(); }; @@ -116,7 +116,7 @@ export function inspectElement( const rendererID = store.getRendererIDForElement(element.id); if (rendererID == null) { const rejectedThenable: RejectedThenable = - (thenable: any); + thenable as any; rejectedThenable.status = 'rejected'; rejectedThenable.reason = new Error( `Could not inspect element with id "${element.id}". No renderer found.`, @@ -133,7 +133,7 @@ export function inspectElement( InspectedElementResponseType, ]) => { const fulfilledThenable: FulfilledThenable = - (thenable: any); + thenable as any; fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = inspectedElement; wake(); @@ -143,7 +143,7 @@ export function inspectElement( console.error(error); const rejectedThenable: RejectedThenable = - (thenable: any); + thenable as any; rejectedThenable.status = 'rejected'; rejectedThenable.reason = error; diff --git a/packages/react-devtools-shared/src/inspectedElementMutableSource.js b/packages/react-devtools-shared/src/inspectedElementMutableSource.js index 4db8c812f4ea..51612a1bb961 100644 --- a/packages/react-devtools-shared/src/inspectedElementMutableSource.js +++ b/packages/react-devtools-shared/src/inspectedElementMutableSource.js @@ -88,7 +88,7 @@ export function inspectElement( let inspectedElement; switch (type) { case 'error': { - const {message, stack, errorType} = ((data: any): InspectElementError); + const {message, stack, errorType} = data as any as InspectElementError; // create a different error class for each error type // and keep useful information from backend. @@ -124,7 +124,7 @@ export function inspectElement( throw Error(`Element "${id}" not found`); case 'full-data': - const fullData = ((data: any): InspectElementFullData); + const fullData = data as any as InspectElementFullData; // New data has come in. // We should replace the data in our local mutable copy. @@ -137,7 +137,7 @@ export function inspectElement( return [inspectedElement, type]; case 'hydrated-path': - const hydratedPathData = ((data: any): InspectElementHydratedPath); + const hydratedPathData = data as any as InspectElementHydratedPath; const {value} = hydratedPathData; // A path has been hydrated. diff --git a/packages/react-devtools-shared/src/utils.js b/packages/react-devtools-shared/src/utils.js index 69c4b5d8aa4f..22e4c444ddfa 100644 --- a/packages/react-devtools-shared/src/utils.js +++ b/packages/react-devtools-shared/src/utils.js @@ -138,7 +138,7 @@ export function getWrappedDisplayName( wrapperName: string, fallbackName?: string, ): string { - const displayName = (outerType: any)?.displayName; + const displayName = (outerType as any)?.displayName; return ( displayName || `${wrapperName}(${getDisplayName(innerType, fallbackName)})` ); @@ -251,8 +251,8 @@ export function printOperationsArray(operations: Array) { switch (operation) { case TREE_OPERATION_ADD: { - const id = ((operations[i + 1]: any): number); - const type = ((operations[i + 2]: any): ElementType); + const id = operations[i + 1] as any as number; + const type = operations[i + 2] as any as ElementType; i += 3; @@ -264,7 +264,7 @@ export function printOperationsArray(operations: Array) { i++; // supportsStrictMode i++; // hasOwnerMetadata } else { - const parentID = ((operations[i]: any): number); + const parentID = operations[i] as any as number; i++; i++; // ownerID @@ -283,11 +283,11 @@ export function printOperationsArray(operations: Array) { break; } case TREE_OPERATION_REMOVE: { - const removeLength = ((operations[i + 1]: any): number); + const removeLength = operations[i + 1] as any as number; i += 2; for (let removeIndex = 0; removeIndex < removeLength; removeIndex++) { - const id = ((operations[i]: any): number); + const id = operations[i] as any as number; i += 1; logs.push(`Remove node ${id}`); @@ -304,8 +304,8 @@ export function printOperationsArray(operations: Array) { break; } case TREE_OPERATION_REORDER_CHILDREN: { - const id = ((operations[i + 1]: any): number); - const numChildren = ((operations[i + 2]: any): number); + const id = operations[i + 1] as any as number; + const numChildren = operations[i + 2] as any as number; i += 3; const children = operations.slice(i, i + numChildren); i += numChildren; @@ -369,11 +369,11 @@ export function printOperationsArray(operations: Array) { break; } case SUSPENSE_TREE_OPERATION_REMOVE: { - const removeLength = ((operations[i + 1]: any): number); + const removeLength = operations[i + 1] as any as number; i += 2; for (let removeIndex = 0; removeIndex < removeLength; removeIndex++) { - const id = ((operations[i]: any): number); + const id = operations[i] as any as number; i += 1; logs.push(`Remove suspense node ${id}`); @@ -382,8 +382,8 @@ export function printOperationsArray(operations: Array) { break; } case SUSPENSE_TREE_OPERATION_REORDER_CHILDREN: { - const id = ((operations[i + 1]: any): number); - const numChildren = ((operations[i + 2]: any): number); + const id = operations[i + 1] as any as number; + const numChildren = operations[i + 2] as any as number; i += 3; const children = operations.slice(i, i + numChildren); i += numChildren; @@ -394,8 +394,8 @@ export function printOperationsArray(operations: Array) { break; } case SUSPENSE_TREE_OPERATION_RESIZE: { - const id = ((operations[i + 1]: any): number); - const numRects = ((operations[i + 2]: any): number); + const id = operations[i + 1] as any as number; + const numRects = operations[i + 2] as any as number; i += 3; if (numRects === -1) { @@ -422,7 +422,7 @@ export function printOperationsArray(operations: Array) { } case SUSPENSE_TREE_OPERATION_SUSPENDERS: { i++; - const changeLength = ((operations[i++]: any): number); + const changeLength = operations[i++] as any as number; for (let changeIndex = 0; changeIndex < changeLength; changeIndex++) { const id = operations[i++]; @@ -651,7 +651,7 @@ export function deletePathInObject( const parent = getInObject(object, path.slice(0, length - 1)); if (parent) { if (isArray(parent)) { - parent.splice(((last: any): number), 1); + parent.splice(last as any as number, 1); } else { delete parent[last]; } @@ -672,7 +672,7 @@ export function renamePathInObject( const lastNew = newPath[length - 1]; parent[lastNew] = parent[lastOld]; if (isArray(parent)) { - parent.splice(((lastOld: any): number), 1); + parent.splice(lastOld as any as number, 1); } else { delete parent[lastOld]; } diff --git a/packages/react-devtools-shell/src/app/DeeplyNestedComponents/index.js b/packages/react-devtools-shell/src/app/DeeplyNestedComponents/index.js index f1369896eda0..5cfdb11c0d31 100644 --- a/packages/react-devtools-shell/src/app/DeeplyNestedComponents/index.js +++ b/packages/react-devtools-shell/src/app/DeeplyNestedComponents/index.js @@ -15,7 +15,7 @@ function wrapWithHoc(Component: () => any, index: number) { return ; } - const displayName = (Component: any).displayName || Component.name; + const displayName = (Component as any).displayName || Component.name; HOC.displayName = `withHoc${index}(${displayName})`; return HOC; diff --git a/packages/react-devtools-shell/src/app/InspectableElements/CustomHooks.js b/packages/react-devtools-shell/src/app/InspectableElements/CustomHooks.js index c0a543d44147..26af74714037 100644 --- a/packages/react-devtools-shell/src/app/InspectableElements/CustomHooks.js +++ b/packages/react-devtools-shell/src/app/InspectableElements/CustomHooks.js @@ -122,8 +122,8 @@ function wrapWithHoc( } const HocWithHooks = wrapWithHoc(FunctionWithHooks); -const Suspendender = React.lazy(() => { - return new Promise(resolve => { +const Suspendender = React.lazy<() => React.Node>(() => { + return new Promise<{default: () => React.Node, ...}>(resolve => { setTimeout(() => { resolve({ default: () => 'Finished!', diff --git a/packages/react-devtools-shell/src/app/ToDoList/ListItem.js b/packages/react-devtools-shell/src/app/ToDoList/ListItem.js index 549d15c31ea2..d8dbb721e858 100644 --- a/packages/react-devtools-shell/src/app/ToDoList/ListItem.js +++ b/packages/react-devtools-shell/src/app/ToDoList/ListItem.js @@ -46,4 +46,4 @@ function ListItem({item, removeItem, toggleItem}: Props) { ); } -export default (memo(ListItem): component(...props: Props)); +export default memo(ListItem) as component(...props: Props); diff --git a/packages/react-devtools-shell/src/app/devtools.js b/packages/react-devtools-shell/src/app/devtools.js index 8f3de74cf67c..dcf9b46afc74 100644 --- a/packages/react-devtools-shell/src/app/devtools.js +++ b/packages/react-devtools-shell/src/app/devtools.js @@ -14,7 +14,7 @@ import {initDevTools} from 'react-devtools-shared/src/devtools'; // $FlowFixMe[cannot-resolve-name] __webpack_public_path__ = '/dist/'; // eslint-disable-line no-undef -const iframe = ((document.getElementById('target'): any): HTMLIFrameElement); +const iframe = document.getElementById('target') as any as HTMLIFrameElement; const {contentDocument, contentWindow} = iframe; @@ -31,13 +31,13 @@ const DevTools = initializeFrontend(contentWindow); // Otherwise the Store may miss important initial tree op codes. activateBackend(contentWindow); -const container = ((document.getElementById('devtools'): any): HTMLElement); +const container = document.getElementById('devtools') as any as HTMLElement; let isTestAppMounted = true; -const mountButton = ((document.getElementById( +const mountButton = document.getElementById( 'mountButton', -): any): HTMLButtonElement); +) as any as HTMLButtonElement; mountButton.addEventListener('click', function () { if (isTestAppMounted) { if (typeof window.unmountTestApp === 'function') { @@ -86,5 +86,5 @@ function inject(sourcePath: string, callback: () => void) { script.onload = callback; script.src = sourcePath; - ((contentDocument.body: any): HTMLBodyElement).appendChild(script); + (contentDocument.body as any as HTMLBodyElement).appendChild(script); } diff --git a/packages/react-devtools-shell/src/app/index.js b/packages/react-devtools-shell/src/app/index.js index 78cd9478362d..0207a8934c2f 100644 --- a/packages/react-devtools-shell/src/app/index.js +++ b/packages/react-devtools-shell/src/app/index.js @@ -54,7 +54,7 @@ const unmountFunctions: Array<() => void | boolean> = []; function createContainer() { const container = document.createElement('div'); - ((document.body: any): HTMLBodyElement).appendChild(container); + (document.body as any as HTMLBodyElement).appendChild(container); return container; } diff --git a/packages/react-devtools-shell/src/e2e-apps/ListApp.js b/packages/react-devtools-shell/src/e2e-apps/ListApp.js index 9cb17188b0ff..58183467696d 100644 --- a/packages/react-devtools-shell/src/e2e-apps/ListApp.js +++ b/packages/react-devtools-shell/src/e2e-apps/ListApp.js @@ -19,7 +19,7 @@ function List() { const inputRef = useRef(null); const addItem = () => { - const input = ((inputRef.current: any): HTMLInputElement); + const input = inputRef.current as any as HTMLInputElement; const text = input.value; input.value = ''; diff --git a/packages/react-devtools-shell/src/e2e-regression/app-legacy.js b/packages/react-devtools-shell/src/e2e-regression/app-legacy.js index 19ad2f0f6d95..54adbca81564 100644 --- a/packages/react-devtools-shell/src/e2e-regression/app-legacy.js +++ b/packages/react-devtools-shell/src/e2e-regression/app-legacy.js @@ -13,7 +13,7 @@ const version = process.env.E2E_APP_REACT_VERSION; function mountApp(App: () => React$Node) { const container = document.createElement('div'); - ((document.body: any): HTMLBodyElement).appendChild(container); + (document.body as any as HTMLBodyElement).appendChild(container); // $FlowFixMe[prop-missing]: These are removed in 19. ReactDOM.render(, container); diff --git a/packages/react-devtools-shell/src/e2e-regression/app.js b/packages/react-devtools-shell/src/e2e-regression/app.js index d0210d323570..2125369dde96 100644 --- a/packages/react-devtools-shell/src/e2e-regression/app.js +++ b/packages/react-devtools-shell/src/e2e-regression/app.js @@ -9,7 +9,7 @@ import ListApp from '../e2e-apps/ListApp'; function mountApp(App: () => React$Node) { const container = document.createElement('div'); - ((document.body: any): HTMLBodyElement).appendChild(container); + (document.body as any as HTMLBodyElement).appendChild(container); const root = ReactDOMClient.createRoot(container); root.render(); diff --git a/packages/react-devtools-shell/src/e2e/app.js b/packages/react-devtools-shell/src/e2e/app.js index 155c545e9ce6..265ebf8a7172 100644 --- a/packages/react-devtools-shell/src/e2e/app.js +++ b/packages/react-devtools-shell/src/e2e/app.js @@ -7,7 +7,7 @@ import * as ReactDOMClient from 'react-dom/client'; const container = document.createElement('div'); -((document.body: any): HTMLBodyElement).appendChild(container); +(document.body as any as HTMLBodyElement).appendChild(container); // TODO We may want to parameterize this app // so that it can load things other than just ToDoList. diff --git a/packages/react-devtools-shell/src/perf-regression/app.js b/packages/react-devtools-shell/src/perf-regression/app.js index 88308e0fcf34..4fa784d55233 100644 --- a/packages/react-devtools-shell/src/perf-regression/app.js +++ b/packages/react-devtools-shell/src/perf-regression/app.js @@ -9,7 +9,7 @@ import App from './apps/index'; function mountApp() { const container = document.createElement('div'); - ((document.body: any): HTMLBodyElement).appendChild(container); + (document.body as any as HTMLBodyElement).appendChild(container); const root = createRoot(container); root.render( diff --git a/packages/react-devtools-timeline/src/EventTooltip.js b/packages/react-devtools-timeline/src/EventTooltip.js index 3d3698c09f94..ab0a409d7ceb 100644 --- a/packages/react-devtools-timeline/src/EventTooltip.js +++ b/packages/react-devtools-timeline/src/EventTooltip.js @@ -293,7 +293,7 @@ const TooltipSchedulingEvent = ({ case 'schedule-force-update': lanes = schedulingEvent.lanes; laneLabels = lanes.map( - lane => ((data.laneToLabelMap.get(lane): any): string), + lane => data.laneToLabelMap.get(lane) as any as string, ); break; } @@ -441,7 +441,7 @@ const TooltipReactMeasure = ({ const [startTime, stopTime] = getBatchRange(batchUID, data); const laneLabels = lanes.map( - lane => ((data.laneToLabelMap.get(lane): any): string), + lane => data.laneToLabelMap.get(lane) as any as string, ); return ( diff --git a/packages/react-devtools-timeline/src/Timeline.js b/packages/react-devtools-timeline/src/Timeline.js index f209309bb0ab..5c427bd9b74c 100644 --- a/packages/react-devtools-timeline/src/Timeline.js +++ b/packages/react-devtools-timeline/src/Timeline.js @@ -57,7 +57,7 @@ export function Timeline(_: {}): React.Node { const [key, setKey] = useState(theme); useLayoutEffect(() => { const pollForTheme = () => { - if (updateColorsToMatchTheme(((ref.current: any): HTMLDivElement))) { + if (updateColorsToMatchTheme(ref.current as any as HTMLDivElement)) { clearInterval(intervalID); setKey(deferredTheme); } diff --git a/packages/react-devtools-timeline/src/TimelineContext.js b/packages/react-devtools-timeline/src/TimelineContext.js index 7835158e9895..a6f52f5fa9d3 100644 --- a/packages/react-devtools-timeline/src/TimelineContext.js +++ b/packages/react-devtools-timeline/src/TimelineContext.js @@ -41,7 +41,7 @@ export type Context = { }; const TimelineContext: ReactContext = createContext( - ((null: any): Context), + null as any as Context, ); TimelineContext.displayName = 'TimelineContext'; diff --git a/packages/react-devtools-timeline/src/TimelineSearchContext.js b/packages/react-devtools-timeline/src/TimelineSearchContext.js index 604dbf180607..2a38dbcfd8c3 100644 --- a/packages/react-devtools-timeline/src/TimelineSearchContext.js +++ b/packages/react-devtools-timeline/src/TimelineSearchContext.js @@ -125,7 +125,7 @@ export type Context = { }; const TimelineSearchContext: ReactContext = createContext( - ((null: any): Context), + null as any as Context, ); TimelineSearchContext.displayName = 'TimelineSearchContext'; diff --git a/packages/react-devtools-timeline/src/content-views/ComponentMeasuresView.js b/packages/react-devtools-timeline/src/content-views/ComponentMeasuresView.js index 0e4a5727e20b..dc1c68045e32 100644 --- a/packages/react-devtools-timeline/src/content-views/ComponentMeasuresView.js +++ b/packages/react-devtools-timeline/src/content-views/ComponentMeasuresView.js @@ -113,8 +113,8 @@ export class ComponentMeasuresView extends View { return false; // Too small to render at this zoom level } - let textFillStyle = ((null: any): string); - let typeLabel = ((null: any): string); + let textFillStyle = null as any as string; + let typeLabel = null as any as string; const drawableRect = intersectionOfRects(componentMeasureRect, rect); context.beginPath(); diff --git a/packages/react-devtools-timeline/src/content-views/SuspenseEventsView.js b/packages/react-devtools-timeline/src/content-views/SuspenseEventsView.js index 43df27e8c92b..3c1fe88e91f7 100644 --- a/packages/react-devtools-timeline/src/content-views/SuspenseEventsView.js +++ b/packages/react-devtools-timeline/src/content-views/SuspenseEventsView.js @@ -122,7 +122,7 @@ export class SuspenseEventsView extends View { baseY += depth * ROW_WITH_BORDER_HEIGHT; - let fillStyle = ((null: any): string); + let fillStyle = null as any as string; if (warning !== null) { fillStyle = showHoverHighlight ? COLORS.WARNING_BACKGROUND_HOVER diff --git a/packages/react-devtools-timeline/src/content-views/utils/text.js b/packages/react-devtools-timeline/src/content-views/utils/text.js index 000a41cb0cdb..30b576c83bed 100644 --- a/packages/react-devtools-timeline/src/content-views/utils/text.js +++ b/packages/react-devtools-timeline/src/content-views/utils/text.js @@ -24,7 +24,7 @@ export function getTextWidth( cachedTextWidths.set(text, measuredWidth); } - return ((measuredWidth: any): number); + return measuredWidth as any as number; } export function trimText( diff --git a/packages/react-devtools-timeline/src/createDataResourceFromImportedFile.js b/packages/react-devtools-timeline/src/createDataResourceFromImportedFile.js index 2b8dfcd266a7..852ad542def5 100644 --- a/packages/react-devtools-timeline/src/createDataResourceFromImportedFile.js +++ b/packages/react-devtools-timeline/src/createDataResourceFromImportedFile.js @@ -22,9 +22,9 @@ export default function createDataResourceFromImportedFile( return createResource( () => { return new Promise((resolve, reject) => { - const promise = ((importFile( + const promise = importFile( file, - ): any): Promise); + ) as any as Promise; promise.then(data => { switch (data.status) { case 'SUCCESS': diff --git a/packages/react-devtools-timeline/src/import-worker/preprocessData.js b/packages/react-devtools-timeline/src/import-worker/preprocessData.js index f54b7b0f7870..50a3091b8eda 100644 --- a/packages/react-devtools-timeline/src/import-worker/preprocessData.js +++ b/packages/react-devtools-timeline/src/import-worker/preprocessData.js @@ -171,9 +171,11 @@ function markWorkStarted( // This array is pre-initialized before processing starts. lanes.forEach(lane => { - ((currentProfilerData.laneToReactMeasureMap.get( - lane, - ): any): ReactMeasure[]).push(measure); + ( + currentProfilerData.laneToReactMeasureMap.get( + lane, + ) as any as Array + ).push(measure); }); } @@ -362,7 +364,7 @@ function processScreenshot( }; // Delay processing until we've extracted snapshot dimensions. - let resolveFn = ((null: any): Function); + let resolveFn = null as any as Function; state.asyncProcessingPromises.push( new Promise(resolve => { resolveFn = resolve; @@ -551,7 +553,7 @@ function processTimelineEvent( currentProfilerData.thrownErrors.push({ componentName, message, - phase: ((phase: any): Phase), + phase: phase as any as Phase, timestamp: startTime, type: 'thrown-error', }); @@ -586,7 +588,7 @@ function processTimelineEvent( depth, duration: null, id, - phase: ((phase: any): Phase), + phase: phase as any as Phase, promiseName: promiseName || null, resolution: 'unresolved', timestamp: startTime, @@ -628,7 +630,7 @@ function processTimelineEvent( } else if (name.startsWith('--render-start-')) { if (state.nextRenderShouldGenerateNewBatchID) { state.nextRenderShouldGenerateNewBatchID = false; - state.batchUID = ((state.uidCounter++: any): BatchUID); + state.batchUID = state.uidCounter++ as any as BatchUID; } // If this render is the result of a nested update, make a note of it. diff --git a/packages/react-devtools-timeline/src/timelineCache.js b/packages/react-devtools-timeline/src/timelineCache.js index ee32e4440f0b..78b2516d8e3e 100644 --- a/packages/react-devtools-timeline/src/timelineCache.js +++ b/packages/react-devtools-timeline/src/timelineCache.js @@ -33,7 +33,7 @@ function readRecord(record: Thenable): T | Error { return React.use(record); } catch (x) { if (record.status === 'rejected') { - return (record.reason: any); + return record.reason as any; } throw x; } @@ -41,7 +41,7 @@ function readRecord(record: Thenable): T | Error { if (record.status === 'fulfilled') { return record.value; } else if (record.status === 'rejected') { - return (record.reason: any); + return record.reason as any; } else { throw record; } @@ -69,13 +69,13 @@ export function importFile(file: File): TimelineData | Error { const wake = () => { // This assumes they won't throw. - callbacks.forEach(callback => callback((thenable: any).value)); + callbacks.forEach(callback => callback((thenable as any).value)); callbacks.clear(); rejectCallbacks.clear(); }; const wakeRejections = () => { // This assumes they won't throw. - rejectCallbacks.forEach(callback => callback((thenable: any).reason)); + rejectCallbacks.forEach(callback => callback((thenable as any).reason)); rejectCallbacks.clear(); callbacks.clear(); }; @@ -86,7 +86,7 @@ export function importFile(file: File): TimelineData | Error { switch (data.status) { case 'SUCCESS': const fulfilledThenable: FulfilledThenable = - (thenable: any); + thenable as any; fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = data.processedData; wake(); @@ -94,7 +94,7 @@ export function importFile(file: File): TimelineData | Error { case 'INVALID_PROFILE_ERROR': case 'UNEXPECTED_ERROR': const rejectedThenable: RejectedThenable = - (thenable: any); + thenable as any; rejectedThenable.status = 'rejected'; rejectedThenable.reason = data.error; wakeRejections(); diff --git a/packages/react-devtools-timeline/src/utils/getBatchRange.js b/packages/react-devtools-timeline/src/utils/getBatchRange.js index 72bf119a0d11..d6f334761bd1 100644 --- a/packages/react-devtools-timeline/src/utils/getBatchRange.js +++ b/packages/react-devtools-timeline/src/utils/getBatchRange.js @@ -26,7 +26,7 @@ function unmemoizedGetBatchRange( throw Error(`Could not find measures with batch UID "${batchUID}"`); } - const lastMeasure = ((measures[measures.length - 1]: any): ReactMeasure); + const lastMeasure = measures[measures.length - 1] as any as ReactMeasure; const stopTime = lastMeasure.timestamp + lastMeasure.duration; if (stopTime < minStartTime) { diff --git a/packages/react-devtools-timeline/src/view-base/VerticalScrollView.js b/packages/react-devtools-timeline/src/view-base/VerticalScrollView.js index 06550e1f837b..d48c6083b865 100644 --- a/packages/react-devtools-timeline/src/view-base/VerticalScrollView.js +++ b/packages/react-devtools-timeline/src/view-base/VerticalScrollView.js @@ -249,9 +249,9 @@ export class VerticalScrollView extends View { if ( this._viewState.viewToMutableViewStateMap.has(this._mutableViewStateKey) ) { - this._scrollState = ((this._viewState.viewToMutableViewStateMap.get( + this._scrollState = this._viewState.viewToMutableViewStateMap.get( this._mutableViewStateKey, - ): any): ScrollState); + ) as any as ScrollState; } else { this._viewState.viewToMutableViewStateMap.set( this._mutableViewStateKey, diff --git a/packages/react-devtools-timeline/src/view-base/resizable/ResizableView.js b/packages/react-devtools-timeline/src/view-base/resizable/ResizableView.js index c66d9af3b503..024ff5056f3e 100644 --- a/packages/react-devtools-timeline/src/view-base/resizable/ResizableView.js +++ b/packages/react-devtools-timeline/src/view-base/resizable/ResizableView.js @@ -107,9 +107,9 @@ export class ResizableView extends View { if ( this._viewState.viewToMutableViewStateMap.has(this._mutableViewStateKey) ) { - this._layoutState = ((this._viewState.viewToMutableViewStateMap.get( + this._layoutState = this._viewState.viewToMutableViewStateMap.get( this._mutableViewStateKey, - ): any): LayoutState); + ) as any as LayoutState; this._updateLayoutStateAndResizeBar(this._layoutState.barOffsetY); } else { diff --git a/packages/react-dom-bindings/src/client/DOMAccessibilityRoles.js b/packages/react-dom-bindings/src/client/DOMAccessibilityRoles.js index 4c1091f2455c..c7f7161f62b2 100644 --- a/packages/react-dom-bindings/src/client/DOMAccessibilityRoles.js +++ b/packages/react-dom-bindings/src/client/DOMAccessibilityRoles.js @@ -80,7 +80,7 @@ function getImplicitRole(element: Element): string | null { } break; case 'INPUT': { - const type = (element: any).type; + const type = (element as any).type; switch (type) { case 'button': case 'image': @@ -111,7 +111,7 @@ function getImplicitRole(element: Element): string | null { } case 'SELECT': - if (element.hasAttribute('multiple') || (element: any).size > 1) { + if (element.hasAttribute('multiple') || (element as any).size > 1) { return 'listbox'; } return 'combobox'; diff --git a/packages/react-dom-bindings/src/client/DOMPropertyOperations.js b/packages/react-dom-bindings/src/client/DOMPropertyOperations.js index 72ed2ae4f924..2ba8ca79f5fa 100644 --- a/packages/react-dom-bindings/src/client/DOMPropertyOperations.js +++ b/packages/react-dom-bindings/src/client/DOMPropertyOperations.js @@ -46,7 +46,7 @@ export function getValueForAttribute( if (__DEV__) { checkAttributeStringCoercion(expected, name); } - if (value === '' + (expected: any)) { + if (value === '' + (expected as any)) { return expected; } return value; @@ -88,7 +88,7 @@ export function getValueForAttributeOnCustomComponent( if (__DEV__) { checkAttributeStringCoercion(expected, name); } - if (value === '' + (expected: any)) { + if (value === '' + (expected as any)) { return expected; } return value; @@ -126,7 +126,7 @@ export function setValueForAttribute( } node.setAttribute( name, - enableTrustedTypesIntegration ? (value: any) : '' + (value: any), + enableTrustedTypesIntegration ? (value as any) : '' + (value as any), ); } } @@ -154,7 +154,7 @@ export function setValueForKnownAttribute( } node.setAttribute( name, - enableTrustedTypesIntegration ? (value: any) : '' + (value: any), + enableTrustedTypesIntegration ? (value as any) : '' + (value as any), ); } @@ -183,7 +183,7 @@ export function setValueForNamespacedAttribute( node.setAttributeNS( namespace, name, - enableTrustedTypesIntegration ? (value: any) : '' + (value: any), + enableTrustedTypesIntegration ? (value as any) : '' + (value as any), ); } @@ -206,22 +206,22 @@ export function setValueForPropertyOnCustomComponent( if (typeof prevValue !== 'function' && prevValue !== null) { // If we previously assigned a non-function type into this node, then // remove it when switching to event listener mode. - if (name in (node: any)) { - (node: any)[name] = null; + if (name in (node as any)) { + (node as any)[name] = null; } else if (node.hasAttribute(name)) { node.removeAttribute(name); } } // $FlowFixMe[incompatible-type] value can't be casted to EventListener. - node.addEventListener(eventName, (value: EventListener), useCapture); + node.addEventListener(eventName, value as EventListener, useCapture); return; } } trackHostMutation(); - if (name in (node: any)) { - (node: any)[name] = value; + if (name in (node as any)) { + (node as any)[name] = value; return; } diff --git a/packages/react-dom-bindings/src/client/ReactDOMComponent.js b/packages/react-dom-bindings/src/client/ReactDOMComponent.js index 78376e4922a2..9ce8253d32a0 100644 --- a/packages/react-dom-bindings/src/client/ReactDOMComponent.js +++ b/packages/react-dom-bindings/src/client/ReactDOMComponent.js @@ -250,7 +250,9 @@ function isExpectedViewTransitionName(htmlElement: HTMLElement): boolean { return false; } const expectedVtName = htmlElement.getAttribute('vt-name'); - const actualVtName: string = (htmlElement.style: any)['view-transition-name']; + const actualVtName: string = (htmlElement.style as any)[ + 'view-transition-name' + ]; if (expectedVtName) { return expectedVtName === actualVtName; } else { @@ -272,7 +274,7 @@ function warnForExtraAttributes( // Skip empty style. It's fine. return; } - const htmlElement = ((domElement: any): HTMLElement); + const htmlElement = domElement as any as HTMLElement; const style = htmlElement.style; const isOnlyVTStyles = (style.length === 1 && style[0] === 'view-transition-name') || @@ -326,7 +328,7 @@ function normalizeHTML(parent: Element, html: string) { parent.namespaceURI === MATH_NAMESPACE || parent.namespaceURI === SVG_NAMESPACE ? parent.ownerDocument.createElementNS( - (parent.namespaceURI: any), + parent.namespaceURI as any, parent.tagName, ) : parent.ownerDocument.createElement(parent.tagName); @@ -347,7 +349,8 @@ function normalizeMarkupForTextOrAttribute(markup: mixed): string { if (__DEV__) { checkHtmlStringCoercion(markup); } - const markupString = typeof markup === 'string' ? markup : '' + (markup: any); + const markupString = + typeof markup === 'string' ? markup : '' + (markup as any); return markupString .replace(NORMALIZE_NEWLINES_REGEX, '\n') .replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, ''); @@ -464,7 +467,7 @@ function setProp( if (__DEV__) { try { // This should always error. - URL.revokeObjectURL(URL.createObjectURL((value: any))); + URL.revokeObjectURL(URL.createObjectURL(value as any)); if (tag === 'source') { console.error( 'Passing Blob, MediaSource or MediaStream to is not supported. ' + @@ -525,9 +528,9 @@ function setProp( if (__DEV__) { checkAttributeStringCoercion(value, key); } - const sanitizedValue = (sanitizeURL( - enableTrustedTypesIntegration ? value : '' + (value: any), - ): any); + const sanitizedValue = sanitizeURL( + enableTrustedTypesIntegration ? value : '' + (value as any), + ) as any; domElement.setAttribute(key, sanitizedValue); break; } @@ -596,9 +599,9 @@ function setProp( if (__DEV__) { checkAttributeStringCoercion(value, key); } - const sanitizedValue = (sanitizeURL( - enableTrustedTypesIntegration ? value : '' + (value: any), - ): any); + const sanitizedValue = sanitizeURL( + enableTrustedTypesIntegration ? value : '' + (value as any), + ) as any; domElement.setAttribute(key, sanitizedValue); break; } @@ -608,7 +611,7 @@ function setProp( if (__DEV__ && typeof value !== 'function') { warnForInvalidEventListener(key, value); } - trapClickOnNonInteractiveElement(((domElement: any): HTMLElement)); + trapClickOnNonInteractiveElement(domElement as any as HTMLElement); } return; } @@ -658,12 +661,12 @@ function setProp( // Note: `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. We have special logic for handling this. case 'multiple': { - (domElement: any).multiple = + (domElement as any).multiple = value && typeof value !== 'function' && typeof value !== 'symbol'; break; } case 'muted': { - (domElement: any).muted = + (domElement as any).muted = value && typeof value !== 'function' && typeof value !== 'symbol'; break; } @@ -699,9 +702,9 @@ function setProp( if (__DEV__) { checkAttributeStringCoercion(value, key); } - const sanitizedValue = (sanitizeURL( - enableTrustedTypesIntegration ? value : '' + (value: any), - ): any); + const sanitizedValue = sanitizeURL( + enableTrustedTypesIntegration ? value : '' + (value as any), + ) as any; domElement.setAttributeNS(xlinkNamespace, 'xlink:href', sanitizedValue); break; } @@ -729,7 +732,7 @@ function setProp( } domElement.setAttribute( key, - enableTrustedTypesIntegration ? (value: any) : '' + (value: any), + enableTrustedTypesIntegration ? (value as any) : '' + (value as any), ); } else { domElement.removeAttribute(key); @@ -800,7 +803,7 @@ function setProp( if (__DEV__) { checkAttributeStringCoercion(value, key); } - domElement.setAttribute(key, (value: any)); + domElement.setAttribute(key, value as any); } else { domElement.removeAttribute(key); } @@ -816,12 +819,12 @@ function setProp( typeof value !== 'function' && typeof value !== 'symbol' && !isNaN(value) && - (value: any) >= 1 + (value as any) >= 1 ) { if (__DEV__) { checkAttributeStringCoercion(value, key); } - domElement.setAttribute(key, (value: any)); + domElement.setAttribute(key, value as any); } else { domElement.removeAttribute(key); } @@ -839,7 +842,7 @@ function setProp( if (__DEV__) { checkAttributeStringCoercion(value, key); } - domElement.setAttribute(key, (value: any)); + domElement.setAttribute(key, value as any); } else { domElement.removeAttribute(key); } @@ -1055,7 +1058,7 @@ function setPropOnCustomElement( if (__DEV__ && typeof value !== 'function') { warnForInvalidEventListener(key, value); } - trapClickOnNonInteractiveElement(((domElement: any): HTMLElement)); + trapClickOnNonInteractiveElement(domElement as any as HTMLElement); } return; } @@ -1344,7 +1347,7 @@ export function setInitialProperties( switch (propKey) { case 'selected': { // TODO: Remove support for selected on option. - (domElement: any).selected = + (domElement as any).selected = propValue && typeof propValue !== 'function' && typeof propValue !== 'symbol'; @@ -1824,7 +1827,7 @@ export function updateProperties( switch (propKey) { case 'selected': { // TODO: Remove support for selected on option. - (domElement: any).selected = false; + (domElement as any).selected = false; break; } default: { @@ -1847,7 +1850,7 @@ export function updateProperties( trackHostMutation(); } // TODO: Remove support for selected on option. - (domElement: any).selected = + (domElement as any).selected = nextProp && typeof nextProp !== 'function' && typeof nextProp !== 'symbol'; @@ -2021,7 +2024,7 @@ function getStylesObjectFromElement(domElement: Element): { [styleName: string]: string, } { const serverValueInObjectForm: {[prop: string]: string} = {}; - const htmlElement: HTMLElement = (domElement: any); + const htmlElement: HTMLElement = domElement as any; const style = htmlElement.style; for (let i = 0; i < style.length; i++) { const styleName: string = style[i]; @@ -2074,7 +2077,7 @@ function diffHydratedStyles( // Trailing semi-colon means this was regenerated. normalizedServerValue[normalizedServerValue.length - 1] === ';' && // TODO: Should we just ignore any style if the style as been manipulated? - hasViewTransition((domElement: any)) + hasViewTransition(domElement as any) ) { // If this had a view transition we might have applied a view transition // name/class and removed it. If that happens, the style attribute gets @@ -2250,7 +2253,7 @@ function hydrateBooleanishAttribute( if (__DEV__) { checkAttributeStringCoercion(value, attributeName); } - if (serverValue === '' + (value: any)) { + if (serverValue === '' + (value as any)) { return; } } @@ -2539,7 +2542,7 @@ function diffHydratedCustomComponent( continue; default: { // This is a DEV-only path - const hostContextDev: HostContextDev = (hostContext: any); + const hostContextDev: HostContextDev = hostContext as any; const hostContextProd = hostContextDev.context; if ( hostContextProd === HostContextNamespaceNone && @@ -2662,26 +2665,26 @@ function diffHydratedGenericElement( continue; case 'multiple': { extraAttributes.delete(propKey); - const serverValue = (domElement: any).multiple; + const serverValue = (domElement as any).multiple; warnForPropDifference(propKey, serverValue, value, serverDifferences); continue; } case 'muted': { extraAttributes.delete(propKey); - const serverValue = (domElement: any).muted; + const serverValue = (domElement as any).muted; warnForPropDifference(propKey, serverValue, value, serverDifferences); continue; } case 'autoFocus': { extraAttributes.delete('autofocus'); - const serverValue = (domElement: any).autofocus; + const serverValue = (domElement as any).autofocus; warnForPropDifference(propKey, serverValue, value, serverDifferences); continue; } case 'data': if (tag !== 'object') { extraAttributes.delete(propKey); - const serverValue = (domElement: any).getAttribute('data'); + const serverValue = (domElement as any).getAttribute('data'); warnForPropDifference(propKey, serverValue, value, serverDifferences); continue; } @@ -2692,7 +2695,7 @@ function diffHydratedGenericElement( if (tag === 'img' || tag === 'video' || tag === 'audio') { try { // Test if this is a compatible object - URL.revokeObjectURL(URL.createObjectURL((value: any))); + URL.revokeObjectURL(URL.createObjectURL(value as any)); hydrateSrcObjectAttribute( domElement, value, @@ -2707,7 +2710,7 @@ function diffHydratedGenericElement( if (__DEV__) { try { // This should always error. - URL.revokeObjectURL(URL.createObjectURL((value: any))); + URL.revokeObjectURL(URL.createObjectURL(value as any)); if (tag === 'source') { console.error( 'Passing Blob, MediaSource or MediaStream to is not supported. ' + @@ -3073,7 +3076,7 @@ function diffHydratedGenericElement( let isMismatchDueToBadCasing = false; // This is a DEV-only path - const hostContextDev: HostContextDev = (hostContext: any); + const hostContextDev: HostContextDev = hostContext as any; const hostContextProd = hostContextDev.context; if ( @@ -3264,7 +3267,7 @@ export function hydrateProperties( if (props.onClick != null) { // TODO: This cast may not be sound for SVG, MathML or custom elements. - trapClickOnNonInteractiveElement(((domElement: any): HTMLElement)); + trapClickOnNonInteractiveElement(domElement as any as HTMLElement); } return true; diff --git a/packages/react-dom-bindings/src/client/ReactDOMComponentTree.js b/packages/react-dom-bindings/src/client/ReactDOMComponentTree.js index 8438410e03a0..71b8630450f0 100644 --- a/packages/react-dom-bindings/src/client/ReactDOMComponentTree.js +++ b/packages/react-dom-bindings/src/client/ReactDOMComponentTree.js @@ -72,22 +72,22 @@ export function detachDeletedInstance(node: Instance): void { if (enableInternalInstanceMap) { internalInstanceMap.delete(node); internalPropsMap.delete(node); - delete (node: any)[internalEventHandlersKey]; - delete (node: any)[internalEventHandlerListenersKey]; - delete (node: any)[internalEventHandlesSetKey]; - delete (node: any)[internalRootNodeResourcesKey]; + delete (node as any)[internalEventHandlersKey]; + delete (node as any)[internalEventHandlerListenersKey]; + delete (node as any)[internalEventHandlesSetKey]; + delete (node as any)[internalRootNodeResourcesKey]; if (__DEV__) { - delete (node: any)[internalInstanceKey]; + delete (node as any)[internalInstanceKey]; } return; } // TODO: This function is only called on host components. I don't think all of // these fields are relevant. - delete (node: any)[internalInstanceKey]; - delete (node: any)[internalPropsKey]; - delete (node: any)[internalEventHandlersKey]; - delete (node: any)[internalEventHandlerListenersKey]; - delete (node: any)[internalEventHandlesSetKey]; + delete (node as any)[internalInstanceKey]; + delete (node as any)[internalPropsKey]; + delete (node as any)[internalEventHandlersKey]; + delete (node as any)[internalEventHandlerListenersKey]; + delete (node as any)[internalEventHandlesSetKey]; } export function precacheFiberNode( @@ -102,11 +102,11 @@ export function precacheFiberNode( if (enableInternalInstanceMap) { internalInstanceMap.set(node, hostInst); if (__DEV__) { - (node: any)[internalInstanceKey] = hostInst; + (node as any)[internalInstanceKey] = hostInst; } return; } - (node: any)[internalInstanceKey] = hostInst; + (node as any)[internalInstanceKey] = hostInst; } export function markContainerAsRoot(hostRoot: Fiber, node: Container): void { @@ -135,9 +135,9 @@ export function isContainerMarkedAsRoot(node: Container): boolean { export function getClosestInstanceFromNode(targetNode: Node): null | Fiber { let targetInst: void | Fiber; if (enableInternalInstanceMap) { - targetInst = internalInstanceMap.get(((targetNode: any): InstanceUnion)); + targetInst = internalInstanceMap.get(targetNode as any as InstanceUnion); } else { - targetInst = (targetNode: any)[internalInstanceKey]; + targetInst = (targetNode as any)[internalInstanceKey]; } if (targetInst) { // Don't return HostRoot, SuspenseComponent or ActivityComponent here. @@ -157,12 +157,12 @@ export function getClosestInstanceFromNode(targetNode: Node): null | Fiber { // If it's not a container, we check if it's an instance. if (enableInternalInstanceMap) { targetInst = - (parentNode: any)[internalContainerInstanceKey] || - internalInstanceMap.get(((parentNode: any): InstanceUnion)); + (parentNode as any)[internalContainerInstanceKey] || + internalInstanceMap.get(parentNode as any as InstanceUnion); } else { targetInst = - (parentNode: any)[internalContainerInstanceKey] || - (parentNode: any)[internalInstanceKey]; + (parentNode as any)[internalContainerInstanceKey] || + (parentNode as any)[internalInstanceKey]; } if (targetInst) { // Since this wasn't the direct target of the event, we might have @@ -229,12 +229,12 @@ export function getInstanceFromNode(node: Node): Fiber | null { let inst: void | null | Fiber; if (enableInternalInstanceMap) { inst = - internalInstanceMap.get(((node: any): InstanceUnion)) || - (node: any)[internalContainerInstanceKey]; + internalInstanceMap.get(node as any as InstanceUnion) || + (node as any)[internalContainerInstanceKey]; } else { inst = - (node: any)[internalInstanceKey] || - (node: any)[internalContainerInstanceKey]; + (node as any)[internalInstanceKey] || + (node as any)[internalContainerInstanceKey]; } if (inst) { const tag = inst.tag; @@ -288,7 +288,7 @@ export function getFiberCurrentPropsFromNode( if (enableInternalInstanceMap) { return internalPropsMap.get(node) || null; } - return (node: any)[internalPropsKey] || null; + return (node as any)[internalPropsKey] || null; } export function updateFiberProps(node: Instance, props: Props): void { @@ -296,15 +296,15 @@ export function updateFiberProps(node: Instance, props: Props): void { internalPropsMap.set(node, props); return; } - (node: any)[internalPropsKey] = props; + (node as any)[internalPropsKey] = props; } export function getEventListenerSet(node: EventTarget): Set { - let elementListenerSet: Set | void = (node: any)[ + let elementListenerSet: Set | void = (node as any)[ internalEventHandlersKey ]; if (elementListenerSet === undefined) { - elementListenerSet = (node: any)[internalEventHandlersKey] = new Set(); + elementListenerSet = (node as any)[internalEventHandlersKey] = new Set(); } return elementListenerSet; } @@ -314,9 +314,9 @@ export function getFiberFromScopeInstance( ): null | Fiber { if (enableScopeAPI) { if (enableInternalInstanceMap) { - return internalInstanceMap.get(((scope: any): InstanceUnion)) || null; + return internalInstanceMap.get(scope as any as InstanceUnion) || null; } - return (scope: any)[internalInstanceKey] || null; + return (scope as any)[internalInstanceKey] || null; } return null; } @@ -325,22 +325,22 @@ export function setEventHandlerListeners( scope: EventTarget | ReactScopeInstance, listeners: Set, ): void { - (scope: any)[internalEventHandlerListenersKey] = listeners; + (scope as any)[internalEventHandlerListenersKey] = listeners; } export function getEventHandlerListeners( scope: EventTarget | ReactScopeInstance, ): null | Set { - return (scope: any)[internalEventHandlerListenersKey] || null; + return (scope as any)[internalEventHandlerListenersKey] || null; } export function addEventHandleToTarget( target: EventTarget | ReactScopeInstance, eventHandle: ReactDOMEventHandle, ): void { - let eventHandles = (target: any)[internalEventHandlesSetKey]; + let eventHandles = (target as any)[internalEventHandlesSetKey]; if (eventHandles === undefined) { - eventHandles = (target: any)[internalEventHandlesSetKey] = new Set(); + eventHandles = (target as any)[internalEventHandlesSetKey] = new Set(); } eventHandles.add(eventHandle); } @@ -349,7 +349,7 @@ export function doesTargetHaveEventHandle( target: EventTarget | ReactScopeInstance, eventHandle: ReactDOMEventHandle, ): boolean { - const eventHandles = (target: any)[internalEventHandlesSetKey]; + const eventHandles = (target as any)[internalEventHandlesSetKey]; if (eventHandles === undefined) { return false; } @@ -357,9 +357,9 @@ export function doesTargetHaveEventHandle( } export function getResourcesFromRoot(root: HoistableRoot): RootResources { - let resources = (root: any)[internalRootNodeResourcesKey]; + let resources = (root as any)[internalRootNodeResourcesKey]; if (!resources) { - resources = (root: any)[internalRootNodeResourcesKey] = { + resources = (root as any)[internalRootNodeResourcesKey] = { hoistableStyles: new Map(), hoistableScripts: new Map(), }; @@ -368,45 +368,45 @@ export function getResourcesFromRoot(root: HoistableRoot): RootResources { } export function isMarkedHoistable(node: Node): boolean { - return !!(node: any)[internalHoistableMarker]; + return !!(node as any)[internalHoistableMarker]; } export function markNodeAsHoistable(node: Node) { - (node: any)[internalHoistableMarker] = true; + (node as any)[internalHoistableMarker] = true; } export function getScrollEndTimer(node: EventTarget): ?TimeoutID { - return (node: any)[internalScrollTimer]; + return (node as any)[internalScrollTimer]; } export function setScrollEndTimer(node: EventTarget, timer: TimeoutID): void { - (node: any)[internalScrollTimer] = timer; + (node as any)[internalScrollTimer] = timer; } export function clearScrollEndTimer(node: EventTarget): void { - (node: any)[internalScrollTimer] = undefined; + (node as any)[internalScrollTimer] = undefined; } export function markNodeAsPendingLoad(node: Node): void { - (node: any)[internalLoadPendingKey] = true; + (node as any)[internalLoadPendingKey] = true; } export function clearPendingLoadOnNode(node: Node): void { - (node: any)[internalLoadPendingKey] = undefined; + (node as any)[internalLoadPendingKey] = undefined; } export function isNodePendingLoad(node: Node): boolean { - return (node: any)[internalLoadPendingKey] === true; + return (node as any)[internalLoadPendingKey] === true; } export function isOwnedInstance(node: Node): boolean { if (enableInternalInstanceMap) { return !!( - (node: any)[internalHoistableMarker] || - internalInstanceMap.has((node: any)) + (node as any)[internalHoistableMarker] || + internalInstanceMap.has(node as any) ); } return !!( - (node: any)[internalHoistableMarker] || (node: any)[internalInstanceKey] + (node as any)[internalHoistableMarker] || (node as any)[internalInstanceKey] ); } diff --git a/packages/react-dom-bindings/src/client/ReactDOMContainer.js b/packages/react-dom-bindings/src/client/ReactDOMContainer.js index df9bcfb44380..bc73db8a00e3 100644 --- a/packages/react-dom-bindings/src/client/ReactDOMContainer.js +++ b/packages/react-dom-bindings/src/client/ReactDOMContainer.js @@ -24,6 +24,6 @@ export function isValidContainer(node: any): boolean { node.nodeType === DOCUMENT_FRAGMENT_NODE || (!disableCommentsAsDOMContainers && node.nodeType === COMMENT_NODE && - (node: any).nodeValue === ' react-mount-point-unstable ')) + (node as any).nodeValue === ' react-mount-point-unstable ')) ); } diff --git a/packages/react-dom-bindings/src/client/ReactDOMEventHandle.js b/packages/react-dom-bindings/src/client/ReactDOMEventHandle.js index 875a9c9697c3..abb66721c2d2 100644 --- a/packages/react-dom-bindings/src/client/ReactDOMEventHandle.js +++ b/packages/react-dom-bindings/src/client/ReactDOMEventHandle.js @@ -35,11 +35,11 @@ type EventHandleOptions = { }; function isValidEventTarget(target: EventTarget | ReactScopeInstance): boolean { - return typeof (target: Object).addEventListener === 'function'; + return typeof (target as Object).addEventListener === 'function'; } function isReactScope(target: EventTarget | ReactScopeInstance): boolean { - return typeof (target: Object).getChildContextValues === 'function'; + return typeof (target as Object).getChildContextValues === 'function'; } function createEventHandleListener( @@ -59,12 +59,12 @@ function registerReactDOMEvent( domEventName: DOMEventName, isCapturePhaseListener: boolean, ): void { - if ((target: any).nodeType === ELEMENT_NODE) { + if ((target as any).nodeType === ELEMENT_NODE) { // Do nothing. We already attached all root listeners. } else if (enableScopeAPI && isReactScope(target)) { // Do nothing. We already attached all root listeners. } else if (isValidEventTarget(target)) { - const eventTarget = ((target: any): EventTarget); + const eventTarget = target as any as EventTarget; // These are valid event targets, but they are also // non-managed React nodes. listenToNativeEventForNonManagedEventTarget( @@ -85,7 +85,7 @@ export function createEventHandle( options?: EventHandleOptions, ): ReactDOMEventHandle { if (enableCreateEventHandleAPI) { - const domEventName = ((type: any): DOMEventName); + const domEventName = type as any as DOMEventName; // We cannot support arbitrary native events with eager root listeners // because the eager strategy relies on knowing the whole list ahead of time. @@ -137,7 +137,7 @@ export function createEventHandle( } targetListeners.add(listener); return () => { - ((targetListeners: any): Set).delete( + (targetListeners as any as Set).delete( listener, ); }; @@ -145,5 +145,5 @@ export function createEventHandle( return eventHandle; } - return (null: any); + return null as any; } diff --git a/packages/react-dom-bindings/src/client/ReactDOMInput.js b/packages/react-dom-bindings/src/client/ReactDOMInput.js index 0ae9824cb849..d38ae2fe0ae2 100644 --- a/packages/react-dom-bindings/src/client/ReactDOMInput.js +++ b/packages/react-dom-bindings/src/client/ReactDOMInput.js @@ -96,7 +96,7 @@ export function updateInput( type: ?string, name: ?string, ) { - const node: HTMLInputElement = (element: any); + const node: HTMLInputElement = element as any; // Temporarily disconnect the input from any radio buttons. // Changing the type or name as the same time as changing the checked value @@ -126,7 +126,7 @@ export function updateInput( (value === 0 && node.value === '') || // We explicitly want to coerce to number here if possible. // eslint-disable-next-line - node.value != (value: any) + node.value != (value as any) ) { node.value = toString(getToStringValue(value)); } @@ -214,7 +214,7 @@ export function initInput( name: ?string, isHydrating: boolean, ) { - const node: HTMLInputElement = (element: any); + const node: HTMLInputElement = element as any; if ( type != null && @@ -235,7 +235,7 @@ export function initInput( // default value provided by the browser. See: #12872 if (isButton && (value === undefined || value === null)) { // We track the value just in case it changes type later on. - track((element: any)); + track(element as any); return; } @@ -342,7 +342,7 @@ export function initInput( } node.name = name; } - track((element: any)); + track(element as any); } export function hydrateInput( @@ -352,7 +352,7 @@ export function hydrateInput( checked: ?boolean, defaultChecked: ?boolean, ): void { - const node: HTMLInputElement = (element: any); + const node: HTMLInputElement = element as any; const defaultValueStr = defaultValue != null ? toString(getToStringValue(defaultValue)) : ''; @@ -370,7 +370,7 @@ export function hydrateInput( // Detach .checked from .defaultChecked but leave user input alone node.checked = node.checked; - const changed = trackHydrated((node: any), initialValue, initialChecked); + const changed = trackHydrated(node as any, initialValue, initialChecked); if (changed) { // If the current value is different, that suggests that the user // changed it before hydration. Queue a replay of the change event. @@ -382,7 +382,7 @@ export function hydrateInput( } export function restoreControlledInputState(element: Element, props: Object) { - const rootNode: HTMLInputElement = (element: any); + const rootNode: HTMLInputElement = element as any; updateInput( rootNode, props.value, @@ -398,7 +398,7 @@ export function restoreControlledInputState(element: Element, props: Object) { let queryRoot: Element = rootNode; while (queryRoot.parentNode) { - queryRoot = ((queryRoot.parentNode: any): Element); + queryRoot = queryRoot.parentNode as any as Element; } // If `rootNode.form` was non-null, then we could try `form.elements`, @@ -418,7 +418,7 @@ export function restoreControlledInputState(element: Element, props: Object) { ); for (let i = 0; i < group.length; i++) { - const otherNode = ((group[i]: any): HTMLInputElement); + const otherNode = group[i] as any as HTMLInputElement; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } @@ -453,7 +453,7 @@ export function restoreControlledInputState(element: Element, props: Object) { // If any updateInput() call set .checked to true, an input in this group // (often, `rootNode` itself) may have become unchecked for (let i = 0; i < group.length; i++) { - const otherNode = ((group[i]: any): HTMLInputElement); + const otherNode = group[i] as any as HTMLInputElement; if (otherNode.form !== rootNode.form) { continue; } diff --git a/packages/react-dom-bindings/src/client/ReactDOMSelect.js b/packages/react-dom-bindings/src/client/ReactDOMSelect.js index 00136aa8175b..6553016fcaee 100644 --- a/packages/react-dom-bindings/src/client/ReactDOMSelect.js +++ b/packages/react-dom-bindings/src/client/ReactDOMSelect.js @@ -69,7 +69,7 @@ function updateOptions( const options: HTMLOptionsCollection = node.options; if (multiple) { - const selectedValues = (propValue: Array); + const selectedValues = propValue as Array; const selectedValue: {[string]: boolean} = {}; for (let i = 0; i < selectedValues.length; i++) { // Prefix to avoid chaos with special keys. @@ -149,7 +149,7 @@ export function initSelect( defaultValue: ?string, multiple: ?boolean, ) { - const node: HTMLSelectElement = (element: any); + const node: HTMLSelectElement = element as any; node.multiple = !!multiple; if (value != null) { updateOptions(node, !!multiple, value, false); @@ -164,7 +164,7 @@ export function hydrateSelect( defaultValue: ?string, multiple: ?boolean, ): void { - const node: HTMLSelectElement = (element: any); + const node: HTMLSelectElement = element as any; const options: HTMLOptionsCollection = node.options; const propValue: any = value != null ? value : defaultValue; @@ -172,7 +172,7 @@ export function hydrateSelect( let changed = false; if (multiple) { - const selectedValues = (propValue: ?Array); + const selectedValues = propValue as ?Array; const selectedValue: {[string]: boolean} = {}; if (selectedValues != null) { for (let i = 0; i < selectedValues.length; i++) { @@ -218,7 +218,7 @@ export function updateSelect( multiple: ?boolean, wasMultiple: ?boolean, ) { - const node: HTMLSelectElement = (element: any); + const node: HTMLSelectElement = element as any; if (value != null) { updateOptions(node, !!multiple, value, false); @@ -234,7 +234,7 @@ export function updateSelect( } export function restoreControlledSelectState(element: Element, props: Object) { - const node: HTMLSelectElement = (element: any); + const node: HTMLSelectElement = element as any; const value = props.value; if (value != null) { diff --git a/packages/react-dom-bindings/src/client/ReactDOMSrcObject.js b/packages/react-dom-bindings/src/client/ReactDOMSrcObject.js index 160d634236d2..f8c25ce5c358 100644 --- a/packages/react-dom-bindings/src/client/ReactDOMSrcObject.js +++ b/packages/react-dom-bindings/src/client/ReactDOMSrcObject.js @@ -10,7 +10,7 @@ export function setSrcObject(domElement: Element, tag: string, value: any) { // We optimistically create the URL regardless of object type. This lets us // support cross-realms and any type that the browser supports like new types. - const url = URL.createObjectURL((value: any)); + const url = URL.createObjectURL(value as any); const loadEvent = tag === 'img' ? 'load' : 'loadstart'; const cleanUp = () => { // Once the object has started loading, then it's already collected by the diff --git a/packages/react-dom-bindings/src/client/ReactDOMTextarea.js b/packages/react-dom-bindings/src/client/ReactDOMTextarea.js index 75fe6b8fabce..be6b20806872 100644 --- a/packages/react-dom-bindings/src/client/ReactDOMTextarea.js +++ b/packages/react-dom-bindings/src/client/ReactDOMTextarea.js @@ -66,7 +66,7 @@ export function updateTextarea( value: ?string, defaultValue: ?string, ) { - const node: HTMLTextAreaElement = (element: any); + const node: HTMLTextAreaElement = element as any; if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. @@ -96,7 +96,7 @@ export function initTextarea( defaultValue: ?string, children: ?string, ) { - const node: HTMLTextAreaElement = (element: any); + const node: HTMLTextAreaElement = element as any; let initialValue = value; @@ -128,7 +128,7 @@ export function initTextarea( } const stringValue = getToStringValue(initialValue); - node.defaultValue = (stringValue: any); // This will be toString:ed. + node.defaultValue = stringValue as any; // This will be toString:ed. // This is in postMount because we need access to the DOM node, which is not // available until after the component has mounted. @@ -146,7 +146,7 @@ export function initTextarea( } } - track((element: any)); + track(element as any); } export function hydrateTextarea( @@ -154,7 +154,7 @@ export function hydrateTextarea( value: ?string, defaultValue: ?string, ): void { - const node: HTMLTextAreaElement = (element: any); + const node: HTMLTextAreaElement = element as any; let initialValue = value; if (initialValue == null) { if (defaultValue == null) { @@ -166,7 +166,7 @@ export function hydrateTextarea( // that any change event that fires will trigger onChange on the actual // current value. const stringValue = toString(getToStringValue(initialValue)); - const changed = trackHydrated((node: any), stringValue, false); + const changed = trackHydrated(node as any, stringValue, false); if (changed) { // If the current value is different, that suggests that the user // changed it before hydration. Queue a replay of the change event. diff --git a/packages/react-dom-bindings/src/client/ReactFiberConfigDOM.js b/packages/react-dom-bindings/src/client/ReactFiberConfigDOM.js index f21c1b6154e6..d4e4dfde408c 100644 --- a/packages/react-dom-bindings/src/client/ReactFiberConfigDOM.js +++ b/packages/react-dom-bindings/src/client/ReactFiberConfigDOM.js @@ -300,7 +300,7 @@ function getOwnerDocumentFromRootContainer( rootContainerElement: Element | Document | DocumentFragment, ): Document { return rootContainerElement.nodeType === DOCUMENT_NODE - ? (rootContainerElement: any) + ? (rootContainerElement as any) : rootContainerElement.ownerDocument; } @@ -314,7 +314,7 @@ export function getRootHostContext( case DOCUMENT_NODE: case DOCUMENT_FRAGMENT_NODE: { type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment'; - const root = (rootContainerInstance: any).documentElement; + const root = (rootContainerInstance as any).documentElement; if (root) { const namespaceURI = root.namespaceURI; context = namespaceURI @@ -398,7 +398,7 @@ export function getChildHostContext( type: string, ): HostContext { if (__DEV__) { - const parentHostContextDev = ((parentHostContext: any): HostContextDev); + const parentHostContextDev = parentHostContext as any as HostContextDev; const context = getChildHostContextProd(parentHostContextDev.context, type); const ancestorInfo = updatedAncestorInfoDev( parentHostContextDev.ancestorInfo, @@ -406,7 +406,7 @@ export function getChildHostContext( ); return {context, ancestorInfo}; } - const parentNamespace = ((parentHostContext: any): HostContextProd); + const parentNamespace = parentHostContext as any as HostContextProd; return getChildHostContextProd(parentNamespace, type); } @@ -432,7 +432,7 @@ export function beforeActiveInstanceBlur(internalInstanceHandle: Object): void { if (enableCreateEventHandleAPI) { ReactBrowserEventEmitterSetEnabled(true); dispatchBeforeDetachedBlur( - (selectionInformation: any).focusedElem, + (selectionInformation as any).focusedElem, internalInstanceHandle, ); ReactBrowserEventEmitterSetEnabled(false); @@ -442,7 +442,7 @@ export function beforeActiveInstanceBlur(internalInstanceHandle: Object): void { export function afterActiveInstanceBlur(): void { if (enableCreateEventHandleAPI) { ReactBrowserEventEmitterSetEnabled(true); - dispatchAfterDetachedBlur((selectionInformation: any).focusedElem); + dispatchAfterDetachedBlur((selectionInformation as any).focusedElem); ReactBrowserEventEmitterSetEnabled(false); } } @@ -534,11 +534,11 @@ export function createInstance( let hostContextProd: HostContextProd; if (__DEV__) { // TODO: take namespace into account when validating. - const hostContextDev: HostContextDev = (hostContext: any); + const hostContextDev: HostContextDev = hostContext as any; validateDOMNesting(type, hostContextDev.ancestorInfo); hostContextProd = hostContextDev.context; } else { - hostContextProd = (hostContext: any); + hostContextProd = hostContext as any; } const ownerDocument = getOwnerDocumentFromRootContainer( @@ -586,7 +586,7 @@ export function createInstance( } div.innerHTML = '