From e7a4dbcefc9e393c41f4a796d522211bc1e60b6f Mon Sep 17 00:00:00 2001 From: Pieter Vanderwerff Date: Wed, 22 Jun 2022 21:36:52 -0700 Subject: [PATCH] Add LTI annotations to function params in xplat/js [1/2] Summary: Add annotations to function parameters required for Flow's Local Type Inference project. This codemod prepares the codebase to match Flow's new typechecking algorithm. The new algorithm will make Flow more reliable and predicatable. Reviewed By: evanyeung Differential Revision: D37353648 fbshipit-source-id: e5a0c685ced85a8ff353d578b373f836b376bb28 --- IntegrationTests/AsyncStorageTest.js | 22 +++++- Libraries/Alert/Alert.js | 2 +- Libraries/Animated/AnimatedEvent.js | 11 +-- Libraries/Animated/AnimatedImplementation.js | 6 +- Libraries/Animated/AnimatedMock.js | 4 +- Libraries/Animated/nodes/AnimatedColor.js | 2 +- Libraries/Animated/nodes/AnimatedValueXY.js | 2 +- Libraries/BatchedBridge/MessageQueue.js | 4 +- Libraries/Components/ScrollView/ScrollView.js | 6 +- Libraries/Components/Touchable/PooledClass.js | 8 +-- Libraries/Components/Touchable/Touchable.js | 13 +++- .../Touchable/TouchableNativeFeedback.js | 4 +- Libraries/Core/Timers/JSTimers.js | 4 +- Libraries/Inspector/NetworkOverlay.js | 9 ++- Libraries/Lists/ViewabilityHelper.js | 10 ++- Libraries/Lists/VirtualizedList.js | 17 +++-- Libraries/Lists/VirtualizedSectionList.js | 13 ++-- Libraries/LogBox/Data/LogBoxData.js | 2 +- .../LogBox/Data/__tests__/LogBoxLog-test.js | 2 +- .../__tests__/LogBoxSymbolication-test.js | 2 +- .../LogBox/UI/LogBoxInspectorStackFrames.js | 11 ++- .../StaticViewConfigValidator-test.js | 4 +- Libraries/Pressability/Pressability.js | 23 +++++-- .../__tests__/Pressability-test.js | 4 +- Libraries/ReactNative/PaperUIManager.js | 2 +- Libraries/Text/Text.js | 14 ++-- Libraries/Utilities/HMRClient.js | 6 +- Libraries/Utilities/ReactNativeTestTools.js | 4 +- Libraries/Vibration/Vibration.js | 2 +- .../androidTest/js/ScrollViewTestModule.js | 15 ++-- .../tools/msggen/src/HeaderWriter.js | 2 +- .../inspector/tools/msggen/src/index.js | 4 +- .../src/generators/RNCodegen.js | 2 +- .../src/generators/components/CppHelpers.js | 8 ++- .../components/GenerateEventEmitterCpp.js | 15 +++- .../components/GenerateEventEmitterH.js | 16 ++++- .../generators/components/GeneratePropsCpp.js | 2 +- .../generators/components/GeneratePropsH.js | 68 ++++++++++++++++--- .../components/GeneratePropsJavaDelegate.js | 15 ++-- .../components/GeneratePropsJavaInterface.js | 11 +-- .../generators/components/GenerateTests.js | 8 ++- .../generators/modules/GenerateModuleCpp.js | 2 +- .../src/generators/modules/GenerateModuleH.js | 2 +- .../src/parsers/flow/components/props.js | 3 +- .../__tests__/module-parser-e2e-test.js | 6 +- .../src/parsers/flow/modules/index.js | 2 +- .../parsers/typescript/components/props.js | 3 +- .../typescript-module-parser-e2e-test.js | 6 +- .../src/parsers/typescript/modules/index.js | 2 +- .../examples/AnimatedGratuitousApp/AnExApp.js | 4 +- .../js/examples/Button/ButtonExample.js | 2 +- .../RNTesterPlatformTestResultView.js | 3 +- .../PointerEventSupport.js | 13 ++-- .../Experimental/W3CPointerEventsExample.js | 5 +- .../FlatList/FlatList-onEndReached.js | 3 +- .../FlatList/FlatList-withSeparators.js | 9 ++- .../js/examples/Image/ImageExample.js | 4 +- .../KeyboardAvoidingViewExample.js | 6 +- .../NativeAnimationsExample.js | 4 +- .../PointerEvents/PointerEventsExample.js | 2 +- .../js/examples/Pressable/PressableExample.js | 4 +- .../rn-tester/js/examples/RTL/RTLExample.js | 26 +++++-- .../SafeAreaView/SafeAreaViewExample.js | 2 +- .../examples/ScrollView/ScrollViewExample.js | 6 +- .../SectionList/SectionList-onEndReached.js | 3 +- .../SectionList-onViewableItemsChanged.js | 7 +- .../SectionList/SectionList-scrollable.js | 9 +-- .../SectionList/SectionList-withSeparators.js | 4 +- .../SwipeableCardExample.js | 6 +- .../TextInput/TextInputExample.ios.js | 14 ++-- .../TextInput/TextInputSharedExamples.js | 14 ++-- .../js/examples/Timer/TimerExample.js | 8 ++- .../js/examples/Touchable/TouchableExample.js | 4 +- .../TurboModule/SampleTurboModuleExample.js | 45 +++++++++++- 74 files changed, 430 insertions(+), 182 deletions(-) diff --git a/IntegrationTests/AsyncStorageTest.js b/IntegrationTests/AsyncStorageTest.js index f3aa7ce8052fe3..42bdbd62965458 100644 --- a/IntegrationTests/AsyncStorageTest.js +++ b/IntegrationTests/AsyncStorageTest.js @@ -33,7 +33,7 @@ const VAL_MERGE_EXPECT = {foo: 1, bar: {hoo: 2, boo: 1}, baz: 2, moo: {a: 3}}; let done = (result: ?boolean) => {}; let updateMessage = (message: string) => {}; -function runTestCase(description: string, fn) { +function runTestCase(description: string, fn: () => void) { updateMessage(description); fn(); } @@ -61,7 +61,20 @@ function stringify( return JSON.stringify(value); } -function expectEqual(lhs, rhs, testname: string) { +function expectEqual( + lhs: ?(any | string | Array>), + rhs: + | null + | string + | { + bar: {boo: number, hoo: number}, + baz: number, + foo: number, + moo: {a: number}, + } + | Array>, + testname: string, +) { expectTrue( !deepDiffer(lhs, rhs), 'Error in test ' + @@ -73,7 +86,10 @@ function expectEqual(lhs, rhs, testname: string) { ); } -function expectAsyncNoError(place, err) { +function expectAsyncNoError( + place: string, + err: ?(Error | string | Array), +) { if (err instanceof Error) { err = err.message; } diff --git a/Libraries/Alert/Alert.js b/Libraries/Alert/Alert.js index d05cf9d6be6bb9..f248e2b9055bbe 100644 --- a/Libraries/Alert/Alert.js +++ b/Libraries/Alert/Alert.js @@ -105,7 +105,7 @@ class Alert { options && options.onDismiss && options.onDismiss(); } }; - const onError = errorMessage => console.warn(errorMessage); + const onError = (errorMessage: string) => console.warn(errorMessage); NativeDialogManagerAndroid.showAlert(config, onError, onAction); } } diff --git a/Libraries/Animated/AnimatedEvent.js b/Libraries/Animated/AnimatedEvent.js index 9aa49926152a86..af1d660a8de794 100644 --- a/Libraries/Animated/AnimatedEvent.js +++ b/Libraries/Animated/AnimatedEvent.js @@ -41,7 +41,7 @@ function attachNativeEvent( // key path inside the `nativeEvent` object. Ex.: ['contentOffset', 'x']. const eventMappings = []; - const traverse = (value, path) => { + const traverse = (value: mixed, path: Array) => { if (value instanceof AnimatedValue) { value.__makeNative(platformConfig); @@ -94,8 +94,8 @@ function attachNativeEvent( }; } -function validateMapping(argMapping, args) { - const validate = (recMapping, recEvt, key) => { +function validateMapping(argMapping: $ReadOnlyArray, args: any) { + const validate = (recMapping: ?Mapping, recEvt: any, key: string) => { if (recMapping instanceof AnimatedValue) { invariant( typeof recEvt === 'number', @@ -223,7 +223,10 @@ class AnimatedEvent { validatedMapping = true; } - const traverse = (recMapping, recEvt) => { + const traverse = ( + recMapping: ?(Mapping | AnimatedValue), + recEvt: any, + ) => { if (recMapping instanceof AnimatedValue) { if (typeof recEvt === 'number') { recMapping.setValue(recEvt); diff --git a/Libraries/Animated/AnimatedImplementation.js b/Libraries/Animated/AnimatedImplementation.js index 84c47e36a1580f..32707208a6ef71 100644 --- a/Libraries/Animated/AnimatedImplementation.js +++ b/Libraries/Animated/AnimatedImplementation.js @@ -94,7 +94,7 @@ const _combineCallbacks = function ( config: $ReadOnly<{...AnimationConfig, ...}>, ) { if (callback && config.onComplete) { - return (...args) => { + return (...args: Array) => { config.onComplete && config.onComplete(...args); callback && callback(...args); }; @@ -308,7 +308,7 @@ const sequence = function ( let current = 0; return { start: function (callback?: ?EndCallback) { - const onComplete = function (result) { + const onComplete = function (result: EndResult) { if (!result.finished) { callback && callback(result); return; @@ -380,7 +380,7 @@ const parallel = function ( } animations.forEach((animation, idx) => { - const cb = function (endResult) { + const cb = function (endResult: EndResult | {finished: boolean}) { hasEnded[idx] = true; doneCount++; if (doneCount === animations.length) { diff --git a/Libraries/Animated/AnimatedMock.js b/Libraries/Animated/AnimatedMock.js index af517502197d53..6efb74fd003261 100644 --- a/Libraries/Animated/AnimatedMock.js +++ b/Libraries/Animated/AnimatedMock.js @@ -10,6 +10,8 @@ 'use strict'; +import type {EndResult} from './animations/Animation'; + const {AnimatedEvent, attachNativeEvent} = require('./AnimatedEvent'); const AnimatedImplementation = require('./AnimatedImplementation'); const AnimatedInterpolation = require('./nodes/AnimatedInterpolation'); @@ -43,7 +45,7 @@ function mockAnimationStart( const guardedCallback = callback == null ? callback - : (...args) => { + : (...args: Array) => { if (inAnimationCallback) { console.warn( 'Ignoring recursive animation callback when running mock animations', diff --git a/Libraries/Animated/nodes/AnimatedColor.js b/Libraries/Animated/nodes/AnimatedColor.js index 8bb31844b22b12..16a87f52800350 100644 --- a/Libraries/Animated/nodes/AnimatedColor.js +++ b/Libraries/Animated/nodes/AnimatedColor.js @@ -249,7 +249,7 @@ export default class AnimatedColor extends AnimatedWithChildren { */ addListener(callback: ColorListenerCallback): string { const id = String(_uniqueId++); - const jointCallback = ({value: number}) => { + const jointCallback = ({value: number}: any) => { callback(this.__getValue()); }; this._listeners[id] = { diff --git a/Libraries/Animated/nodes/AnimatedValueXY.js b/Libraries/Animated/nodes/AnimatedValueXY.js index 71d1129c6bcb1f..c54a9d9d6f55e5 100644 --- a/Libraries/Animated/nodes/AnimatedValueXY.js +++ b/Libraries/Animated/nodes/AnimatedValueXY.js @@ -177,7 +177,7 @@ class AnimatedValueXY extends AnimatedWithChildren { */ addListener(callback: ValueXYListenerCallback): string { const id = String(_uniqueId++); - const jointCallback = ({value: number}) => { + const jointCallback = ({value: number}: any) => { callback(this.__getValue()); }; this._listeners[id] = { diff --git a/Libraries/BatchedBridge/MessageQueue.js b/Libraries/BatchedBridge/MessageQueue.js index ed32d725da1d27..2ae720810ac9e4 100644 --- a/Libraries/BatchedBridge/MessageQueue.js +++ b/Libraries/BatchedBridge/MessageQueue.js @@ -252,7 +252,7 @@ class MessageQueue { // folly-convertible. As a special case, if a prop value is a // function it is permitted here, and special-cased in the // conversion. - const isValidArgument = val => { + const isValidArgument = (val: mixed) => { switch (typeof val) { case 'undefined': case 'boolean': @@ -286,7 +286,7 @@ class MessageQueue { // Replacement allows normally non-JSON-convertible values to be // seen. There is ambiguity with string values, but in context, // it should at least be a strong hint. - const replacer = (key, val) => { + const replacer = (key: string, val: $FlowFixMe) => { const t = typeof val; if (t === 'function') { return '<>'; diff --git a/Libraries/Components/ScrollView/ScrollView.js b/Libraries/Components/ScrollView/ScrollView.js index bc7c06aae7b093..09ef62817f4878 100644 --- a/Libraries/Components/ScrollView/ScrollView.js +++ b/Libraries/Components/ScrollView/ScrollView.js @@ -1107,7 +1107,7 @@ class ScrollView extends React.Component { } }; - _getKeyForIndex(index, childArray) { + _getKeyForIndex(index: $FlowFixMe, childArray: $FlowFixMe) { const child = childArray[index]; return child && child.key; } @@ -1140,7 +1140,7 @@ class ScrollView extends React.Component { } } - _onStickyHeaderLayout(index, event, key) { + _onStickyHeaderLayout(index: $FlowFixMe, event: $FlowFixMe, key: $FlowFixMe) { const {stickyHeaderIndices} = this.props; if (!stickyHeaderIndices) { return; @@ -1822,7 +1822,7 @@ const styles = StyleSheet.create({ }, }); -function Wrapper(props, ref) { +function Wrapper(props, ref: (mixed => mixed) | {current: mixed, ...}) { return ; } Wrapper.displayName = 'ScrollView'; diff --git a/Libraries/Components/Touchable/PooledClass.js b/Libraries/Components/Touchable/PooledClass.js index 139f1657ea48d3..7a57583a69cb2d 100644 --- a/Libraries/Components/Touchable/PooledClass.js +++ b/Libraries/Components/Touchable/PooledClass.js @@ -18,7 +18,7 @@ import invariant from 'invariant'; * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ -const oneArgumentPooler = function (copyFieldsFrom) { +const oneArgumentPooler = function (copyFieldsFrom: any) { const Klass = this; // eslint-disable-line consistent-this if (Klass.instancePool.length) { const instance = Klass.instancePool.pop(); @@ -29,7 +29,7 @@ const oneArgumentPooler = function (copyFieldsFrom) { } }; -const twoArgumentPooler = function (a1, a2) { +const twoArgumentPooler = function (a1: any, a2: any) { const Klass = this; // eslint-disable-line consistent-this if (Klass.instancePool.length) { const instance = Klass.instancePool.pop(); @@ -40,7 +40,7 @@ const twoArgumentPooler = function (a1, a2) { } }; -const threeArgumentPooler = function (a1, a2, a3) { +const threeArgumentPooler = function (a1: any, a2: any, a3: any) { const Klass = this; // eslint-disable-line consistent-this if (Klass.instancePool.length) { const instance = Klass.instancePool.pop(); @@ -51,7 +51,7 @@ const threeArgumentPooler = function (a1, a2, a3) { } }; -const fourArgumentPooler = function (a1, a2, a3, a4) { +const fourArgumentPooler = function (a1: any, a2: any, a3: any, a4: any) { const Klass = this; // eslint-disable-line consistent-this if (Klass.instancePool.length) { const instance = Klass.instancePool.pop(); diff --git a/Libraries/Components/Touchable/Touchable.js b/Libraries/Components/Touchable/Touchable.js index 47fdfa892d0662..b4ec927840fe37 100644 --- a/Libraries/Components/Touchable/Touchable.js +++ b/Libraries/Components/Touchable/Touchable.js @@ -21,7 +21,18 @@ import type {ColorValue} from '../../StyleSheet/StyleSheet'; import type {EdgeInsetsProp} from '../../StyleSheet/EdgeInsetsPropType'; import type {PressEvent} from '../../Types/CoreEventTypes'; -const extractSingleTouch = nativeEvent => { +const extractSingleTouch = (nativeEvent: { + +changedTouches: $ReadOnlyArray, + +force?: number, + +identifier: number, + +locationX: number, + +locationY: number, + +pageX: number, + +pageY: number, + +target: ?number, + +timestamp: number, + +touches: $ReadOnlyArray, +}) => { const touches = nativeEvent.touches; const changedTouches = nativeEvent.changedTouches; const hasTouches = touches && touches.length > 0; diff --git a/Libraries/Components/Touchable/TouchableNativeFeedback.js b/Libraries/Components/Touchable/TouchableNativeFeedback.js index 910a51c5e30994..2064a81c36c632 100644 --- a/Libraries/Components/Touchable/TouchableNativeFeedback.js +++ b/Libraries/Components/Touchable/TouchableNativeFeedback.js @@ -312,11 +312,11 @@ class TouchableNativeFeedback extends React.Component { const getBackgroundProp = Platform.OS === 'android' - ? (background, useForeground) => + ? (background, useForeground: boolean) => useForeground && TouchableNativeFeedback.canUseNativeForeground() ? {nativeForegroundAndroid: background} : {nativeBackgroundAndroid: background} - : (background, useForeground) => null; + : (background, useForeground: boolean) => null; TouchableNativeFeedback.displayName = 'TouchableNativeFeedback'; diff --git a/Libraries/Core/Timers/JSTimers.js b/Libraries/Core/Timers/JSTimers.js index 8682a1dcda572b..2ef47d88c0a6be 100644 --- a/Libraries/Core/Timers/JSTimers.js +++ b/Libraries/Core/Timers/JSTimers.js @@ -274,7 +274,7 @@ const JSTimers = { const timeout = options && options.timeout; const id = _allocateCallback( timeout != null - ? deadline => { + ? (deadline: any) => { const timeoutId = requestIdleCallbackTimeouts[id]; if (timeoutId) { JSTimers.clearTimeout(timeoutId); @@ -364,7 +364,7 @@ const JSTimers = { // error one at a time for (let ii = 1; ii < errorCount; ii++) { JSTimers.setTimeout( - (error => { + ((error: Error) => { throw error; }).bind(null, errors[ii]), 0, diff --git a/Libraries/Inspector/NetworkOverlay.js b/Libraries/Inspector/NetworkOverlay.js index a510f357f04697..79f2f301a43c3c 100644 --- a/Libraries/Inspector/NetworkOverlay.js +++ b/Libraries/Inspector/NetworkOverlay.js @@ -10,6 +10,8 @@ 'use strict'; +import type {RenderItemProps} from '../Lists/VirtualizedList'; + const ScrollView = require('../Components/ScrollView/ScrollView'); const TouchableHighlight = require('../Components/Touchable/TouchableHighlight'); const View = require('../Components/View/View'); @@ -326,7 +328,10 @@ class NetworkOverlay extends React.Component { WebSocketInterceptor.disableInterception(); } - _renderItem = ({item, index}): React.Element => { + _renderItem = ({ + item, + index, + }: RenderItemProps): React.Element => { const tableRowViewStyle = [ styles.tableRow, index % 2 === 1 ? styles.tableRowOdd : styles.tableRowEven, @@ -358,7 +363,7 @@ class NetworkOverlay extends React.Component { ); }; - _renderItemDetail(id) { + _renderItemDetail(id: number) { const requestItem = this.state.requests[id]; const details = Object.keys(requestItem).map(key => { if (key === 'id') { diff --git a/Libraries/Lists/ViewabilityHelper.js b/Libraries/Lists/ViewabilityHelper.js index 2e000c8f01ffe1..ae91b25ab68d3b 100644 --- a/Libraries/Lists/ViewabilityHelper.js +++ b/Libraries/Lists/ViewabilityHelper.js @@ -259,9 +259,13 @@ class ViewabilityHelper { } _onUpdateSync( - viewableIndicesToCheck, - onViewableItemsChanged, - createViewToken, + viewableIndicesToCheck: Array, + onViewableItemsChanged: ({ + changed: Array, + viewableItems: Array, + ... + }) => void, + createViewToken: (index: number, isViewable: boolean) => ViewToken, ) { // Filter out indices that have gone out of view since this call was scheduled. viewableIndicesToCheck = viewableIndicesToCheck.filter(ii => diff --git a/Libraries/Lists/VirtualizedList.js b/Libraries/Lists/VirtualizedList.js index 685a0269e7eed5..1897a5d3dcb26e 100644 --- a/Libraries/Lists/VirtualizedList.js +++ b/Libraries/Lists/VirtualizedList.js @@ -10,7 +10,7 @@ import type {ScrollResponderType} from '../Components/ScrollView/ScrollView'; import type {ViewStyleProp} from '../StyleSheet/StyleSheet'; -import type {LayoutEvent} from '../Types/CoreEventTypes'; +import type {LayoutEvent, ScrollEvent} from '../Types/CoreEventTypes'; import type { ViewabilityConfig, ViewabilityConfigCallbackPair, @@ -1713,7 +1713,7 @@ class VirtualizedList extends React.PureComponent { } } - _onScrollBeginDrag = (e): void => { + _onScrollBeginDrag = (e: ScrollEvent): void => { this._nestedChildLists.forEach(childList => { childList.ref && childList.ref._onScrollBeginDrag(e); }); @@ -1724,7 +1724,7 @@ class VirtualizedList extends React.PureComponent { this.props.onScrollBeginDrag && this.props.onScrollBeginDrag(e); }; - _onScrollEndDrag = (e): void => { + _onScrollEndDrag = (e: ScrollEvent): void => { this._nestedChildLists.forEach(childList => { childList.ref && childList.ref._onScrollEndDrag(e); }); @@ -1736,14 +1736,14 @@ class VirtualizedList extends React.PureComponent { this.props.onScrollEndDrag && this.props.onScrollEndDrag(e); }; - _onMomentumScrollBegin = (e): void => { + _onMomentumScrollBegin = (e: ScrollEvent): void => { this._nestedChildLists.forEach(childList => { childList.ref && childList.ref._onMomentumScrollBegin(e); }); this.props.onMomentumScrollBegin && this.props.onMomentumScrollBegin(e); }; - _onMomentumScrollEnd = (e): void => { + _onMomentumScrollEnd = (e: ScrollEvent): void => { this._nestedChildLists.forEach(childList => { childList.ref && childList.ref._onMomentumScrollEnd(e); }); @@ -2033,7 +2033,12 @@ class CellRenderer extends React.Component< ); }; - _renderElement(renderItem, ListItemComponent, item, index) { + _renderElement( + renderItem: any, + ListItemComponent: any, + item: any, + index: any, + ) { if (renderItem && ListItemComponent) { console.warn( 'VirtualizedList: Both ListItemComponent and renderItem props are present. ListItemComponent will take' + diff --git a/Libraries/Lists/VirtualizedSectionList.js b/Libraries/Lists/VirtualizedSectionList.js index 396ad7b58ca2de..f17d6e992a5506 100644 --- a/Libraries/Lists/VirtualizedSectionList.js +++ b/Libraries/Lists/VirtualizedSectionList.js @@ -392,21 +392,24 @@ class VirtualizedSectionList< } }; - _updatePropsFor = (cellKey, value) => { + _updatePropsFor = (cellKey: string, value: any) => { const updateProps = this._updatePropsMap[cellKey]; if (updateProps != null) { updateProps(value); } }; - _updateHighlightFor = (cellKey, value) => { + _updateHighlightFor = (cellKey: string, value: boolean) => { const updateHighlight = this._updateHighlightMap[cellKey]; if (updateHighlight != null) { updateHighlight(value); } }; - _setUpdateHighlightFor = (cellKey, updateHighlightFn) => { + _setUpdateHighlightFor = ( + cellKey: string, + updateHighlightFn: ?(boolean) => void, + ) => { if (updateHighlightFn != null) { this._updateHighlightMap[cellKey] = updateHighlightFn; } else { @@ -414,7 +417,7 @@ class VirtualizedSectionList< } }; - _setUpdatePropsFor = (cellKey, updatePropsFn) => { + _setUpdatePropsFor = (cellKey: string, updatePropsFn: ?(boolean) => void) => { if (updatePropsFn != null) { this._updatePropsMap[cellKey] = updatePropsFn; } else { @@ -449,7 +452,7 @@ class VirtualizedSectionList< _updateHighlightMap: {[string]: (boolean) => void} = {}; _updatePropsMap: {[string]: void | (boolean => void)} = {}; _listRef: ?React.ElementRef; - _captureRef = ref => { + _captureRef = (ref: null | React$ElementRef>) => { this._listRef = ref; }; } diff --git a/Libraries/LogBox/Data/LogBoxData.js b/Libraries/LogBox/Data/LogBoxData.js index 77b13401823a80..1fb9d59bbec138 100644 --- a/Libraries/LogBox/Data/LogBoxData.js +++ b/Libraries/LogBox/Data/LogBoxData.js @@ -133,7 +133,7 @@ function handleUpdate(): void { } } -function appendNewLog(newLog) { +function appendNewLog(newLog: LogBoxLog) { // Don't want store these logs because they trigger a // state update when we add them to the store. if (isMessageIgnored(newLog.message.content)) { diff --git a/Libraries/LogBox/Data/__tests__/LogBoxLog-test.js b/Libraries/LogBox/Data/__tests__/LogBoxLog-test.js index e683cea4a3ee5b..bd26449ba0a96d 100644 --- a/Libraries/LogBox/Data/__tests__/LogBoxLog-test.js +++ b/Libraries/LogBox/Data/__tests__/LogBoxLog-test.js @@ -49,7 +49,7 @@ function getLogBoxSymbolication(): {| return (require('../LogBoxSymbolication'): any); } -const createStack = methodNames => +const createStack = (methodNames: Array) => methodNames.map(methodName => ({ column: null, file: 'file://path/to/file.js', diff --git a/Libraries/LogBox/Data/__tests__/LogBoxSymbolication-test.js b/Libraries/LogBox/Data/__tests__/LogBoxSymbolication-test.js index 8c16348598cb64..1d35a1e9867ffd 100644 --- a/Libraries/LogBox/Data/__tests__/LogBoxSymbolication-test.js +++ b/Libraries/LogBox/Data/__tests__/LogBoxSymbolication-test.js @@ -22,7 +22,7 @@ const symbolicateStackTrace: JestMockFn< Promise>, > = (require('../../../Core/Devtools/symbolicateStackTrace'): any); -const createStack = methodNames => +const createStack = (methodNames: Array) => methodNames.map(methodName => ({ column: null, file: 'file://path/to/file.js', diff --git a/Libraries/LogBox/UI/LogBoxInspectorStackFrames.js b/Libraries/LogBox/UI/LogBoxInspectorStackFrames.js index b1227d9a6836a1..08eec15d11f441 100644 --- a/Libraries/LogBox/UI/LogBoxInspectorStackFrames.js +++ b/Libraries/LogBox/UI/LogBoxInspectorStackFrames.js @@ -8,6 +8,10 @@ * @format */ +import type {StackFrame} from '../../Core/NativeExceptionsManager'; +import type {Stack} from '../Data/LogBoxSymbolication'; +import type LogBoxLog from '../Data/LogBoxLog'; + import * as React from 'react'; import StyleSheet from '../../StyleSheet/StyleSheet'; import Text from '../../Text/Text'; @@ -18,8 +22,6 @@ import LogBoxInspectorStackFrame from './LogBoxInspectorStackFrame'; import LogBoxInspectorSection from './LogBoxInspectorSection'; import * as LogBoxStyle from './LogBoxStyle'; import openFileInEditor from '../../Core/Devtools/openFileInEditor'; -import type {Stack} from '../Data/LogBoxSymbolication'; -import type LogBoxLog from '../Data/LogBoxLog'; type Props = $ReadOnly<{| log: LogBoxLog, @@ -111,7 +113,10 @@ function LogBoxInspectorStackFrames(props: Props): React.Node { ); } -function StackFrameList(props) { +function StackFrameList(props: { + list: Stack | Array, + status: string | 'COMPLETE' | 'FAILED' | 'NONE' | 'PENDING', +}) { return ( <> {props.list.map((frame, index) => { diff --git a/Libraries/NativeComponent/__tests__/StaticViewConfigValidator-test.js b/Libraries/NativeComponent/__tests__/StaticViewConfigValidator-test.js index d39afe9f416da6..28b471938c7709 100644 --- a/Libraries/NativeComponent/__tests__/StaticViewConfigValidator-test.js +++ b/Libraries/NativeComponent/__tests__/StaticViewConfigValidator-test.js @@ -210,10 +210,10 @@ StaticViewConfigValidator: Invalid static view config for 'RCTView'. }); function expectSVCToNotMatchNVC( - name, + name: string, nativeViewConfig, staticViewConfig, - message, + message: string, ) { const validationResult = StaticViewConfigValidator.validate( name, diff --git a/Libraries/Pressability/Pressability.js b/Libraries/Pressability/Pressability.js index 4f70f006cf45ce..54b80e5b0c7eaf 100644 --- a/Libraries/Pressability/Pressability.js +++ b/Libraries/Pressability/Pressability.js @@ -255,20 +255,20 @@ const Transitions = Object.freeze({ }, }); -const isActiveSignal = signal => +const isActiveSignal = (signal: TouchState) => signal === 'RESPONDER_ACTIVE_PRESS_IN' || signal === 'RESPONDER_ACTIVE_LONG_PRESS_IN'; -const isActivationSignal = signal => +const isActivationSignal = (signal: TouchState) => signal === 'RESPONDER_ACTIVE_PRESS_OUT' || signal === 'RESPONDER_ACTIVE_PRESS_IN'; -const isPressInSignal = signal => +const isPressInSignal = (signal: TouchState) => signal === 'RESPONDER_INACTIVE_PRESS_IN' || signal === 'RESPONDER_ACTIVE_PRESS_IN' || signal === 'RESPONDER_ACTIVE_LONG_PRESS_IN'; -const isTerminalSignal = signal => +const isTerminalSignal = (signal: TouchSignal) => signal === 'RESPONDER_TERMINATED' || signal === 'RESPONDER_RELEASE'; const DEFAULT_LONG_PRESS_DELAY_MS = 500; @@ -808,7 +808,14 @@ export default class Pressability { } } - _measureCallback = (left, top, width, height, pageX, pageY) => { + _measureCallback = ( + left: number, + top: number, + width: number, + height: number, + pageX: number, + pageY: number, + ) => { if (!left && !top && !width && !height && !pageX && !pageY) { return; } @@ -918,7 +925,11 @@ export default class Pressability { } } -function normalizeDelay(delay: ?number, min = 0, fallback = 0): number { +function normalizeDelay( + delay: ?number, + min: number = 0, + fallback: number = 0, +): number { return Math.max(min, delay ?? fallback); } diff --git a/Libraries/Pressability/__tests__/Pressability-test.js b/Libraries/Pressability/__tests__/Pressability-test.js index cbb48e1acf8eb2..42af85f3dff36b 100644 --- a/Libraries/Pressability/__tests__/Pressability-test.js +++ b/Libraries/Pressability/__tests__/Pressability-test.js @@ -105,7 +105,7 @@ const mockUIManagerMeasure = (options?: {|delay: number|}) => { }); }; -const createMockTargetEvent = registrationName => { +const createMockTargetEvent = (registrationName: string) => { const nativeEvent = { target: 42, }; @@ -132,7 +132,7 @@ const createMockTargetEvent = registrationName => { }; }; -const createMockMouseEvent = registrationName => { +const createMockMouseEvent = (registrationName: string) => { const nativeEvent = { clientX: 0, clientY: 0, diff --git a/Libraries/ReactNative/PaperUIManager.js b/Libraries/ReactNative/PaperUIManager.js index ad83e6248af1f6..b331ca2e95212c 100644 --- a/Libraries/ReactNative/PaperUIManager.js +++ b/Libraries/ReactNative/PaperUIManager.js @@ -114,7 +114,7 @@ const UIManagerJS = { // $FlowFixMe[prop-missing] NativeUIManager.getViewManagerConfig = UIManagerJS.getViewManagerConfig; -function lazifyViewManagerConfig(viewName) { +function lazifyViewManagerConfig(viewName: string) { const viewConfig = getConstants()[viewName]; viewManagerConfigs[viewName] = viewConfig; if (viewConfig.Manager) { diff --git a/Libraries/Text/Text.js b/Libraries/Text/Text.js index eafa5e3b277d43..57b6a2ea82ca28 100644 --- a/Libraries/Text/Text.js +++ b/Libraries/Text/Text.js @@ -8,6 +8,8 @@ * @format */ +import type {PressEvent} from '../Types/CoreEventTypes'; + import Platform from '../Utilities/Platform'; import * as PressabilityDebug from '../Pressability/PressabilityDebug'; import usePressability from '../Pressability/usePressability'; @@ -73,11 +75,11 @@ const Text: React.AbstractComponent< pressRectOffset: pressRetentionOffset, onLongPress, onPress, - onPressIn(event) { + onPressIn(event: PressEvent) { setHighlighted(!suppressHighlighting); onPressIn?.(event); }, - onPressOut(event) { + onPressOut(event: PressEvent) { setHighlighted(false); onPressOut?.(event); }, @@ -106,25 +108,25 @@ const Text: React.AbstractComponent< eventHandlers == null ? null : { - onResponderGrant(event) { + onResponderGrant(event: PressEvent) { eventHandlers.onResponderGrant(event); if (onResponderGrant != null) { onResponderGrant(event); } }, - onResponderMove(event) { + onResponderMove(event: PressEvent) { eventHandlers.onResponderMove(event); if (onResponderMove != null) { onResponderMove(event); } }, - onResponderRelease(event) { + onResponderRelease(event: PressEvent) { eventHandlers.onResponderRelease(event); if (onResponderRelease != null) { onResponderRelease(event); } }, - onResponderTerminate(event) { + onResponderTerminate(event: PressEvent) { eventHandlers.onResponderTerminate(event); if (onResponderTerminate != null) { onResponderTerminate(event); diff --git a/Libraries/Utilities/HMRClient.js b/Libraries/Utilities/HMRClient.js index 63da957ef37028..16870e57071128 100644 --- a/Libraries/Utilities/HMRClient.js +++ b/Libraries/Utilities/HMRClient.js @@ -256,7 +256,7 @@ Error: ${e.message}`; }, }; -function setHMRUnavailableReason(reason) { +function setHMRUnavailableReason(reason: string) { invariant(hmrClient, 'Expected HMRClient.setup() call at startup.'); if (hmrUnavailableReason !== null) { // Don't show more than one warning. @@ -273,7 +273,7 @@ function setHMRUnavailableReason(reason) { } } -function registerBundleEntryPoints(client) { +function registerBundleEntryPoints(client: MetroHMRClient) { if (hmrUnavailableReason != null) { DevSettings.reload('Bundle Splitting – Metro disconnected'); return; @@ -290,7 +290,7 @@ function registerBundleEntryPoints(client) { } } -function flushEarlyLogs(client) { +function flushEarlyLogs(client: MetroHMRClient) { try { pendingLogs.forEach(([level, data]) => { HMRClient.log(level, data); diff --git a/Libraries/Utilities/ReactNativeTestTools.js b/Libraries/Utilities/ReactNativeTestTools.js index 4c7bc91b419d47..dfbb46780bc0a5 100644 --- a/Libraries/Utilities/ReactNativeTestTools.js +++ b/Libraries/Utilities/ReactNativeTestTools.js @@ -180,7 +180,9 @@ function renderAndEnforceStrictMode(element: React.Node): any { } function renderWithStrictMode(element: React.Node): ReactTestRendererType { - const WorkAroundBugWithStrictModeInTestRenderer = prps => prps.children; + const WorkAroundBugWithStrictModeInTestRenderer = (prps: { + children: React.Node, + }) => prps.children; const StrictMode = (React: $FlowFixMe).StrictMode; return ReactTestRenderer.create( diff --git a/Libraries/Vibration/Vibration.js b/Libraries/Vibration/Vibration.js index 840527de0de416..f862235d79ef58 100644 --- a/Libraries/Vibration/Vibration.js +++ b/Libraries/Vibration/Vibration.js @@ -40,7 +40,7 @@ function vibrateByPattern(pattern: Array, repeat: boolean = false) { } function vibrateScheduler( - id, + id: number, pattern: Array, repeat: boolean, nextIndex: number, diff --git a/ReactAndroid/src/androidTest/js/ScrollViewTestModule.js b/ReactAndroid/src/androidTest/js/ScrollViewTestModule.js index c0c1969a7379a9..50a8b3c8bfa36f 100644 --- a/ReactAndroid/src/androidTest/js/ScrollViewTestModule.js +++ b/ReactAndroid/src/androidTest/js/ScrollViewTestModule.js @@ -10,6 +10,11 @@ 'use strict'; +import type { + PressEvent, + ScrollEvent, +} from 'react-native/Libraries/Types/CoreEventTypes'; + const BatchedBridge = require('react-native/Libraries/BatchedBridge/BatchedBridge'); const React = require('react'); @@ -26,8 +31,6 @@ const {ScrollListener} = NativeModules; const NUM_ITEMS = 100; -import type {PressEvent} from 'react-native/Libraries/Types/CoreEventTypes'; - // Shared by integration tests for ScrollView and HorizontalScrollView let scrollViewApp: ScrollViewTestApp | HorizontalScrollViewTestApp; @@ -61,28 +64,28 @@ const getInitialState = function () { }; }; -const onScroll = function (e) { +const onScroll = function (e: ScrollEvent) { ScrollListener.onScroll( e.nativeEvent.contentOffset.x, e.nativeEvent.contentOffset.y, ); }; -const onScrollBeginDrag = function (e) { +const onScrollBeginDrag = function (e: ScrollEvent) { ScrollListener.onScrollBeginDrag( e.nativeEvent.contentOffset.x, e.nativeEvent.contentOffset.y, ); }; -const onScrollEndDrag = function (e) { +const onScrollEndDrag = function (e: ScrollEvent) { ScrollListener.onScrollEndDrag( e.nativeEvent.contentOffset.x, e.nativeEvent.contentOffset.y, ); }; -const onItemPress = function (itemNumber) { +const onItemPress = function (itemNumber: number) { ScrollListener.onItemPress(itemNumber); }; diff --git a/ReactCommon/hermes/inspector/tools/msggen/src/HeaderWriter.js b/ReactCommon/hermes/inspector/tools/msggen/src/HeaderWriter.js index b8f5cdb32e8a61..5784f9f2f261bd 100644 --- a/ReactCommon/hermes/inspector/tools/msggen/src/HeaderWriter.js +++ b/ReactCommon/hermes/inspector/tools/msggen/src/HeaderWriter.js @@ -70,7 +70,7 @@ export class HeaderWriter { this.stream.write('struct UnknownRequest;\n\n'); const namespaceMap: Map> = new Map(); - const addToMap = function (type) { + const addToMap = function (type: Type | Command | Event) { const domain = type.domain; let types = namespaceMap.get(domain); if (!types) { diff --git a/ReactCommon/hermes/inspector/tools/msggen/src/index.js b/ReactCommon/hermes/inspector/tools/msggen/src/index.js index eb9a4f3ba96501..1a137ac7170759 100644 --- a/ReactCommon/hermes/inspector/tools/msggen/src/index.js +++ b/ReactCommon/hermes/inspector/tools/msggen/src/index.js @@ -32,7 +32,7 @@ type Descriptor = {| events: Array, |}; -function mergeDomains(original, extra) { +function mergeDomains(original: any, extra: any) { return {...original, domains: original.domains.concat(extra.domains)}; } @@ -186,7 +186,7 @@ function filterReachableFromRoots( // Sort commands and events so the code is easier to read. Types have to be // topologically sorted as explained above. - const comparator = (a, b) => { + const comparator = (a: Command | Event, b: Command | Event) => { const id1 = a.getDebuggerName(); const id2 = b.getDebuggerName(); return id1 < id2 ? -1 : id1 > id2 ? 1 : 0; diff --git a/packages/react-native-codegen/src/generators/RNCodegen.js b/packages/react-native-codegen/src/generators/RNCodegen.js index dd9cd1283958cc..78004999db3a0b 100644 --- a/packages/react-native-codegen/src/generators/RNCodegen.js +++ b/packages/react-native-codegen/src/generators/RNCodegen.js @@ -198,7 +198,7 @@ module.exports = { ): boolean { schemaValidator.validate(schema); - function composePath(intermediate) { + function composePath(intermediate: string) { return path.join(outputDirectory, intermediate, libraryName); } diff --git a/packages/react-native-codegen/src/generators/components/CppHelpers.js b/packages/react-native-codegen/src/generators/components/CppHelpers.js index 92ee6c2529b1d0..608fd6d98127a5 100644 --- a/packages/react-native-codegen/src/generators/components/CppHelpers.js +++ b/packages/react-native-codegen/src/generators/components/CppHelpers.js @@ -57,7 +57,13 @@ function getImports( ): Set { const imports: Set = new Set(); - function addImportsForNativeName(name) { + function addImportsForNativeName( + name: + | 'ColorPrimitive' + | 'EdgeInsetsPrimitive' + | 'ImageSourcePrimitive' + | 'PointPrimitive', + ) { switch (name) { case 'ColorPrimitive': return; diff --git a/packages/react-native-codegen/src/generators/components/GenerateEventEmitterCpp.js b/packages/react-native-codegen/src/generators/components/GenerateEventEmitterCpp.js index 59690c61e6e48e..cb82e3903b0663 100644 --- a/packages/react-native-codegen/src/generators/components/GenerateEventEmitterCpp.js +++ b/packages/react-native-codegen/src/generators/components/GenerateEventEmitterCpp.js @@ -9,6 +9,7 @@ */ 'use strict'; +import type {EventTypeShape} from '../../CodegenSchema'; const {generateEventStructName} = require('./CppHelpers.js'); @@ -90,7 +91,11 @@ void ${className}EventEmitter::${eventName}() const { } `.trim(); -function generateSetter(variableName, propertyName, propertyParts) { +function generateSetter( + variableName: string, + propertyName: string, + propertyParts: $ReadOnlyArray, +) { const trailingPeriod = propertyParts.length === 0 ? '' : '.'; const eventChain = `event.${propertyParts.join( '.', @@ -99,7 +104,11 @@ function generateSetter(variableName, propertyName, propertyParts) { return `${variableName}.setProperty(runtime, "${propertyName}", ${eventChain}`; } -function generateEnumSetter(variableName, propertyName, propertyParts) { +function generateEnumSetter( + variableName: string, + propertyName: string, + propertyParts: $ReadOnlyArray, +) { const trailingPeriod = propertyParts.length === 0 ? '' : '.'; const eventChain = `event.${propertyParts.join( '.', @@ -177,7 +186,7 @@ function generateSetters( return propSetters; } -function generateEvent(componentName: string, event): string { +function generateEvent(componentName: string, event: EventTypeShape): string { // This is a gross hack necessary because native code is sending // events named things like topChange to JS which is then converted back to // call the onChange prop. We should be consistent throughout the system. diff --git a/packages/react-native-codegen/src/generators/components/GenerateEventEmitterH.js b/packages/react-native-codegen/src/generators/components/GenerateEventEmitterH.js index 8eba4d79f6ab2c..269567575c02f0 100644 --- a/packages/react-native-codegen/src/generators/components/GenerateEventEmitterH.js +++ b/packages/react-native-codegen/src/generators/components/GenerateEventEmitterH.js @@ -135,7 +135,11 @@ function getNativeTypeFromAnnotation( throw new Error(`Received invalid event property type ${type}`); } } -function generateEnum(structs, options, nameParts) { +function generateEnum( + structs: StructsMap, + options: $ReadOnlyArray, + nameParts: Array, +) { const structName = generateEventStructName(nameParts); const fields = options .map((option, index) => `${toSafeCppString(option)}`) @@ -218,7 +222,10 @@ function generateStruct( ); } -function generateStructs(componentName: string, component): string { +function generateStructs( + componentName: string, + component: ComponentShape, +): string { const structs: StructsMap = new Map(); component.events.forEach(event => { @@ -244,7 +251,10 @@ function generateEvent(componentName: string, event: EventTypeShape): string { return `void ${event.name}() const;`; } -function generateEvents(componentName: string, component): string { +function generateEvents( + componentName: string, + component: ComponentShape, +): string { return component.events .map(event => generateEvent(componentName, event)) .join('\n\n' + ' '); diff --git a/packages/react-native-codegen/src/generators/components/GeneratePropsCpp.js b/packages/react-native-codegen/src/generators/components/GeneratePropsCpp.js index 145b8467757ae7..ad9d6aac61f45a 100644 --- a/packages/react-native-codegen/src/generators/components/GeneratePropsCpp.js +++ b/packages/react-native-codegen/src/generators/components/GeneratePropsCpp.js @@ -74,7 +74,7 @@ function generatePropsString(componentName: string, component: ComponentShape) { .join(',\n' + ' '); } -function getClassExtendString(component): string { +function getClassExtendString(component: ComponentShape): string { const extendString = ' ' + component.extendsProps diff --git a/packages/react-native-codegen/src/generators/components/GeneratePropsH.js b/packages/react-native-codegen/src/generators/components/GeneratePropsH.js index fc8202a1c09e7e..26521b0cbb1936 100644 --- a/packages/react-native-codegen/src/generators/components/GeneratePropsH.js +++ b/packages/react-native-codegen/src/generators/components/GeneratePropsH.js @@ -9,6 +9,16 @@ */ 'use strict'; +import type { + StringTypeAnnotation, + ReservedPropTypeAnnotation, + ObjectTypeAnnotation, + Int32TypeAnnotation, + FloatTypeAnnotation, + DoubleTypeAnnotation, + ComponentShape, + BooleanTypeAnnotation, +} from '../../CodegenSchema'; const { convertDefaultTypeToString, @@ -257,7 +267,7 @@ static inline std::string toString(const ${enumMask} &value) { } `.trim(); -function getClassExtendString(component): string { +function getClassExtendString(component: ComponentShape): string { if (component.extendsProps.length === 0) { throw new Error('Invalid: component.extendsProps is empty'); } @@ -286,7 +296,29 @@ function getClassExtendString(component): string { function getNativeTypeFromAnnotation( componentName: string, - prop, + prop: + | NamedShape + | { + name: string, + typeAnnotation: + | $FlowFixMe + | DoubleTypeAnnotation + | FloatTypeAnnotation + | BooleanTypeAnnotation + | Int32TypeAnnotation + | StringTypeAnnotation + | ObjectTypeAnnotation + | ReservedPropTypeAnnotation + | { + +default: string, + +options: $ReadOnlyArray, + +type: 'StringEnumTypeAnnotation', + } + | { + +elementType: ObjectTypeAnnotation, + +type: 'ArrayTypeAnnotation', + }, + }, nameParts: $ReadOnlyArray, ): string { const typeAnnotation = prop.typeAnnotation; @@ -400,7 +432,10 @@ function generateArrayEnumString( }); } -function generateStringEnum(componentName, prop) { +function generateStringEnum( + componentName: string, + prop: NamedShape, +) { const typeAnnotation = prop.typeAnnotation; if (typeAnnotation.type === 'StringEnumTypeAnnotation') { const values: $ReadOnlyArray = typeAnnotation.options; @@ -435,7 +470,10 @@ function generateStringEnum(componentName, prop) { return ''; } -function generateIntEnum(componentName, prop) { +function generateIntEnum( + componentName: string, + prop: NamedShape, +) { const typeAnnotation = prop.typeAnnotation; if (typeAnnotation.type === 'Int32EnumTypeAnnotation') { const values: $ReadOnlyArray = typeAnnotation.options; @@ -476,7 +514,10 @@ function generateIntEnum(componentName, prop) { return ''; } -function generateEnumString(componentName: string, component): string { +function generateEnumString( + componentName: string, + component: ComponentShape, +): string { return component.props .map(prop => { if ( @@ -567,7 +608,13 @@ function getLocalImports( ): Set { const imports: Set = new Set(); - function addImportsForNativeName(name) { + function addImportsForNativeName( + name: + | 'ColorPrimitive' + | 'EdgeInsetsPrimitive' + | 'ImageSourcePrimitive' + | 'PointPrimitive', + ) { switch (name) { case 'ColorPrimitive': imports.add('#include '); @@ -635,7 +682,10 @@ function getLocalImports( return imports; } -function generateStructsForComponent(componentName: string, component): string { +function generateStructsForComponent( + componentName: string, + component: ComponentShape, +): string { const structs = generateStructs(componentName, component.props, []); const structArray = Array.from(structs.values()); if (structArray.length < 1) { @@ -646,8 +696,8 @@ function generateStructsForComponent(componentName: string, component): string { function generateStructs( componentName: string, - properties, - nameParts, + properties: $ReadOnlyArray>, + nameParts: Array, ): StructsMap { const structs: StructsMap = new Map(); properties.forEach(prop => { diff --git a/packages/react-native-codegen/src/generators/components/GeneratePropsJavaDelegate.js b/packages/react-native-codegen/src/generators/components/GeneratePropsJavaDelegate.js index 17bdbda66ad175..f39fe2a51d9055 100644 --- a/packages/react-native-codegen/src/generators/components/GeneratePropsJavaDelegate.js +++ b/packages/react-native-codegen/src/generators/components/GeneratePropsJavaDelegate.js @@ -9,6 +9,7 @@ */ 'use strict'; +import type {CommandParamTypeAnnotation} from '../../CodegenSchema'; import type { NamedShape, @@ -170,7 +171,10 @@ function generatePropCasesString( }`; } -function getCommandArgJavaType(param, index) { +function getCommandArgJavaType( + param: NamedShape, + index: number, +) { const {typeAnnotation} = param; switch (typeAnnotation.type) { @@ -229,7 +233,7 @@ function generateCommandCasesString( return commandMethods; } -function getClassExtendString(component): string { +function getClassExtendString(component: ComponentShape): string { const extendString = component.extendsProps .map(extendProps => { switch (extendProps.type) { @@ -251,7 +255,7 @@ function getClassExtendString(component): string { return extendString; } -function getDelegateImports(component) { +function getDelegateImports(component: ComponentShape) { const imports = getImports(component, 'delegate'); // The delegate needs ReadableArray for commands always. // The interface doesn't always need it @@ -265,7 +269,10 @@ function getDelegateImports(component) { return imports; } -function generateMethods(propsString, commandsString): string { +function generateMethods( + propsString: string, + commandsString: null | string, +): string { return [ PropSetterTemplate({propCases: propsString}), commandsString != null diff --git a/packages/react-native-codegen/src/generators/components/GeneratePropsJavaInterface.js b/packages/react-native-codegen/src/generators/components/GeneratePropsJavaInterface.js index 581564d10fc08c..5afeeb6e51db10 100644 --- a/packages/react-native-codegen/src/generators/components/GeneratePropsJavaInterface.js +++ b/packages/react-native-codegen/src/generators/components/GeneratePropsJavaInterface.js @@ -9,6 +9,7 @@ */ 'use strict'; +import type {CommandParamTypeAnnotation} from '../../CodegenSchema'; import type { NamedShape, @@ -56,13 +57,13 @@ public interface ${className} { } `; -function addNullable(imports) { +function addNullable(imports: Set) { imports.add('import androidx.annotation.Nullable;'); } function getJavaValueForProp( prop: NamedShape, - imports, + imports: Set, ): string { const typeAnnotation = prop.typeAnnotation; @@ -126,7 +127,7 @@ function getJavaValueForProp( } } -function generatePropsString(component: ComponentShape, imports) { +function generatePropsString(component: ComponentShape, imports: Set) { if (component.props.length === 0) { return '// No props'; } @@ -140,7 +141,7 @@ function generatePropsString(component: ComponentShape, imports) { .join('\n' + ' '); } -function getCommandArgJavaType(param) { +function getCommandArgJavaType(param: NamedShape) { const {typeAnnotation} = param; switch (typeAnnotation.type) { @@ -198,7 +199,7 @@ function generateCommandsString( .join('\n' + ' '); } -function getClassExtendString(component): string { +function getClassExtendString(component: ComponentShape): string { const extendString = component.extendsProps .map(extendProps => { switch (extendProps.type) { diff --git a/packages/react-native-codegen/src/generators/components/GenerateTests.js b/packages/react-native-codegen/src/generators/components/GenerateTests.js index dbaffefdd7217c..cfefaa318bd946 100644 --- a/packages/react-native-codegen/src/generators/components/GenerateTests.js +++ b/packages/react-native-codegen/src/generators/components/GenerateTests.js @@ -9,6 +9,7 @@ */ 'use strict'; +import type {PropTypeAnnotation, ComponentShape} from '../../CodegenSchema'; import type {SchemaType} from '../../CodegenSchema'; const {getImports, toSafeCppString} = require('./CppHelpers'); @@ -76,7 +77,10 @@ TEST(${componentName}_${testName}, etc) { } `; -function getTestCasesForProp(propName, typeAnnotation) { +function getTestCasesForProp( + propName: string, + typeAnnotation: PropTypeAnnotation, +) { const cases = []; if (typeAnnotation.type === 'StringEnumTypeAnnotation') { typeAnnotation.options.forEach(option => @@ -134,7 +138,7 @@ function getTestCasesForProp(propName, typeAnnotation) { return cases; } -function generateTestsString(name, component) { +function generateTestsString(name: string, component: ComponentShape) { function createTest({testName, propName, propValue, raw = false}: TestCase) { const value = !raw && typeof propValue === 'string' ? `"${propValue}"` : propValue; diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js index 5d7d481383b44a..046e86b1c65e0a 100644 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js +++ b/packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js @@ -127,7 +127,7 @@ function serializeArg( realTypeAnnotation = resolveAlias(realTypeAnnotation.name); } - function wrap(callback) { + function wrap(callback: (val: string) => string) { const val = `args[${index}]`; const expression = callback(val); diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleH.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleH.js index d21f33c928355c..1f518d3f47e0f9 100644 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleH.js +++ b/packages/react-native-codegen/src/generators/modules/GenerateModuleH.js @@ -119,7 +119,7 @@ function translatePrimitiveJSTypeToCpp( realTypeAnnotation = resolveAlias(realTypeAnnotation.name); } - function wrap(type) { + function wrap(type: string) { return nullable ? `std::optional<${type}>` : type; } diff --git a/packages/react-native-codegen/src/parsers/flow/components/props.js b/packages/react-native-codegen/src/parsers/flow/components/props.js index 1c7982da781226..003f47bed2e29e 100644 --- a/packages/react-native-codegen/src/parsers/flow/components/props.js +++ b/packages/react-native-codegen/src/parsers/flow/components/props.js @@ -9,6 +9,7 @@ */ 'use strict'; +import type {ASTNode} from '../utils'; const {getValueFromTypes} = require('../utils.js'); @@ -177,7 +178,7 @@ function getTypeAnnotationForArray( function getTypeAnnotation( name: string, - annotation, + annotation: $FlowFixMe | ASTNode, defaultValue: $FlowFixMe | null, withNullDefault: boolean, types: TypeDeclarationMap, diff --git a/packages/react-native-codegen/src/parsers/flow/modules/__tests__/module-parser-e2e-test.js b/packages/react-native-codegen/src/parsers/flow/modules/__tests__/module-parser-e2e-test.js index 2601d945f74821..25c9d178d7d0ac 100644 --- a/packages/react-native-codegen/src/parsers/flow/modules/__tests__/module-parser-e2e-test.js +++ b/packages/react-native-codegen/src/parsers/flow/modules/__tests__/module-parser-e2e-test.js @@ -712,7 +712,7 @@ describe('Flow Module Parser', () => { const RETURN_TYPE_DESCRIPTION = IS_RETURN_TYPE_NULLABLE ? 'a nullable' : 'a non-nullable'; - const annotateRet = retType => + const annotateRet = (retType: string) => IS_RETURN_TYPE_NULLABLE ? `?${retType}` : retType; function parseReturnType( @@ -927,7 +927,7 @@ describe('Flow Module Parser', () => { ? 'an optional' : 'a required'; - function annotateProp(propName, propType) { + function annotateProp(propName: string, propType: string) { if (nullable && optional) { return `${propName}?: ?${propType}`; } @@ -1229,7 +1229,7 @@ describe('Flow Module Parser', () => { }); }); -function parseModule(source) { +function parseModule(source: string) { const schema = parseString(source, `${MODULE_NAME}.js`); const module = schema.modules.NativeFoo; invariant( diff --git a/packages/react-native-codegen/src/parsers/flow/modules/index.js b/packages/react-native-codegen/src/parsers/flow/modules/index.js index 10153679a65767..38ce80db4e746c 100644 --- a/packages/react-native-codegen/src/parsers/flow/modules/index.js +++ b/packages/react-native-codegen/src/parsers/flow/modules/index.js @@ -549,7 +549,7 @@ function buildPropertySchema( }; } -function isModuleInterface(node) { +function isModuleInterface(node: $FlowFixMe) { return ( node.type === 'InterfaceDeclaration' && node.extends.length === 1 && diff --git a/packages/react-native-codegen/src/parsers/typescript/components/props.js b/packages/react-native-codegen/src/parsers/typescript/components/props.js index 68d1d85e0b3891..1d58f0d2445ada 100644 --- a/packages/react-native-codegen/src/parsers/typescript/components/props.js +++ b/packages/react-native-codegen/src/parsers/typescript/components/props.js @@ -9,6 +9,7 @@ */ 'use strict'; +import type {ASTNode} from '../utils'; const {getValueFromTypes} = require('../utils.js'); @@ -221,7 +222,7 @@ function getTypeAnnotationForArray( function getTypeAnnotation( name: string, - annotation, + annotation: $FlowFixMe | ASTNode, defaultValue: $FlowFixMe | null, withNullDefault: boolean, types: TypeDeclarationMap, diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/typescript-module-parser-e2e-test.js b/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/typescript-module-parser-e2e-test.js index caa2043ca55cb5..99b7702f5fd640 100644 --- a/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/typescript-module-parser-e2e-test.js +++ b/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/typescript-module-parser-e2e-test.js @@ -714,7 +714,7 @@ describe('TypeScript Module Parser', () => { const RETURN_TYPE_DESCRIPTION = IS_RETURN_TYPE_NULLABLE ? 'a nullable' : 'a non-nullable'; - const annotateRet = retType => + const annotateRet = (retType: string) => IS_RETURN_TYPE_NULLABLE ? `${retType} | null | void` : retType; function parseReturnType( @@ -927,7 +927,7 @@ describe('TypeScript Module Parser', () => { ? 'an optional' : 'a required'; - function annotateProp(propName, propType) { + function annotateProp(propName: string, propType: string) { if (nullable && optional) { return `${propName}?: ${propType} | null | void`; } @@ -1231,7 +1231,7 @@ describe('TypeScript Module Parser', () => { }); }); -function parseModule(source) { +function parseModule(source: string) { const schema = parseString(source, `${MODULE_NAME}.ts`); const module = schema.modules.NativeFoo; invariant( diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/index.js b/packages/react-native-codegen/src/parsers/typescript/modules/index.js index 66041f980dfa91..a2048bbdc822d3 100644 --- a/packages/react-native-codegen/src/parsers/typescript/modules/index.js +++ b/packages/react-native-codegen/src/parsers/typescript/modules/index.js @@ -551,7 +551,7 @@ function buildPropertySchema( }; } -function isModuleInterface(node) { +function isModuleInterface(node: $FlowFixMe) { return ( node.type === 'TSInterfaceDeclaration' && node.extends.length === 1 && diff --git a/packages/rn-tester/js/examples/AnimatedGratuitousApp/AnExApp.js b/packages/rn-tester/js/examples/AnimatedGratuitousApp/AnExApp.js index 171c61b2b0c85b..3788016c810b1a 100644 --- a/packages/rn-tester/js/examples/AnimatedGratuitousApp/AnExApp.js +++ b/packages/rn-tester/js/examples/AnimatedGratuitousApp/AnExApp.js @@ -189,7 +189,7 @@ class Circle extends React.Component { ); } - _toggleIsActive = velocity => { + _toggleIsActive = (velocity: void) => { const config = {tension: 30, friction: 7}; if (this.state.isActive) { Animated.spring(this.props.openVal, { @@ -311,7 +311,7 @@ function distance(p1: Point, p2: Point): number { return dx * dx + dy * dy; } -function moveToClosest({activeKey, keys, restLayouts}, position) { +function moveToClosest({activeKey, keys, restLayouts}: any, position: Point) { const activeIdx = -1; let closestIdx = activeIdx; let minDist = Infinity; diff --git a/packages/rn-tester/js/examples/Button/ButtonExample.js b/packages/rn-tester/js/examples/Button/ButtonExample.js index dd97ad5a78f414..cc04f1e0bea7cf 100644 --- a/packages/rn-tester/js/examples/Button/ButtonExample.js +++ b/packages/rn-tester/js/examples/Button/ButtonExample.js @@ -15,7 +15,7 @@ const React = require('react'); const {Alert, Button, View, StyleSheet} = require('react-native'); const {RNTesterThemeContext} = require('../../components/RNTesterTheme'); -function onButtonPress(buttonName) { +function onButtonPress(buttonName: string) { Alert.alert(`Your application has been ${buttonName}!`); } diff --git a/packages/rn-tester/js/examples/Experimental/PlatformTest/RNTesterPlatformTestResultView.js b/packages/rn-tester/js/examples/Experimental/PlatformTest/RNTesterPlatformTestResultView.js index 4faee1f310ab1c..6e8eb5f8851a38 100644 --- a/packages/rn-tester/js/examples/Experimental/PlatformTest/RNTesterPlatformTestResultView.js +++ b/packages/rn-tester/js/examples/Experimental/PlatformTest/RNTesterPlatformTestResultView.js @@ -8,6 +8,7 @@ * @flow */ +import type {RenderItemProps} from 'react-native/Libraries/Lists/VirtualizedList'; import type { ViewStyleProp, TextStyle, @@ -73,7 +74,7 @@ const TableRow = React.memo( }, ); -function renderTableRow({item}) { +function renderTableRow({item}: RenderItemProps) { return ; } diff --git a/packages/rn-tester/js/examples/Experimental/W3CPointerEventPlatformTests/PointerEventSupport.js b/packages/rn-tester/js/examples/Experimental/W3CPointerEventPlatformTests/PointerEventSupport.js index 99208285875479..0fa7ceb46b5bb2 100644 --- a/packages/rn-tester/js/examples/Experimental/W3CPointerEventPlatformTests/PointerEventSupport.js +++ b/packages/rn-tester/js/examples/Experimental/W3CPointerEventPlatformTests/PointerEventSupport.js @@ -60,19 +60,19 @@ export function check_PointerEvent( // * if the attribute is "readonly", it cannot be changed // TA: 1.1, 1.2 const idl_type_check = { - long: function (v) { + long: function (v: any) { return typeof v === 'number' && Math.round(v) === v; }, - float: function (v) { + float: function (v: any) { return typeof v === 'number'; }, - string: function (v) { + string: function (v: any) { return typeof v === 'string'; }, - boolean: function (v) { + boolean: function (v: any) { return typeof v === 'boolean'; }, - object: function (v) { + object: function (v: any) { return typeof v === 'object'; }, }; @@ -189,7 +189,8 @@ export function useTestEventHandler( handler: (event: any, eventName: string) => void, ): ViewProps { const eventProps: any = useMemo(() => { - const handlerFactory = eventName => event => handler(event, eventName); + const handlerFactory = (eventName: string) => (event: any) => + handler(event, eventName); const props = {}; for (const eventName of eventNames) { const eventPropName = diff --git a/packages/rn-tester/js/examples/Experimental/W3CPointerEventsExample.js b/packages/rn-tester/js/examples/Experimental/W3CPointerEventsExample.js index 5cf7c0e865018e..d105decc169c62 100644 --- a/packages/rn-tester/js/examples/Experimental/W3CPointerEventsExample.js +++ b/packages/rn-tester/js/examples/Experimental/W3CPointerEventsExample.js @@ -8,6 +8,7 @@ * @flow */ +import type {PointerEvent} from 'react-native/Libraries/Types/CoreEventTypes'; import {Button, StyleSheet, ScrollView, View, Text} from 'react-native'; import * as React from 'react'; import type {ViewProps} from 'react-native/Libraries/Components/View/ViewPropTypes'; @@ -55,7 +56,7 @@ function EventfulView(props: {| } = props; const [tag, setTag] = React.useState(''); - const eventLog = eventName => event => { + const eventLog = (eventName: string) => (event: PointerEvent) => { // $FlowFixMe Using private property log(`${name} - ${eventName} - target: ${event.target._nativeTag}`); }; @@ -159,7 +160,7 @@ function PointerEventScaffolding({ }) { const [eventsLog, setEventsLog] = React.useState(''); const clear = () => setEventsLog(''); - const log = eventStr => { + const log = (eventStr: string) => { setEventsLog(currentEventsLog => `${eventStr}\n${currentEventsLog}`); }; return ( diff --git a/packages/rn-tester/js/examples/FlatList/FlatList-onEndReached.js b/packages/rn-tester/js/examples/FlatList/FlatList-onEndReached.js index c2b206020a7f6b..7d5c0437d3ea16 100644 --- a/packages/rn-tester/js/examples/FlatList/FlatList-onEndReached.js +++ b/packages/rn-tester/js/examples/FlatList/FlatList-onEndReached.js @@ -16,7 +16,8 @@ import * as React from 'react'; export function FlatList_onEndReached(): React.Node { const [output, setOutput] = React.useState(''); const exampleProps = { - onEndReached: info => setOutput('onEndReached'), + onEndReached: (info: {distanceFromEnd: number, ...}) => + setOutput('onEndReached'), onEndReachedThreshold: 0, }; const ref = React.useRef(null); diff --git a/packages/rn-tester/js/examples/FlatList/FlatList-withSeparators.js b/packages/rn-tester/js/examples/FlatList/FlatList-withSeparators.js index b73288462980c3..9a0f0294891f9e 100644 --- a/packages/rn-tester/js/examples/FlatList/FlatList-withSeparators.js +++ b/packages/rn-tester/js/examples/FlatList/FlatList-withSeparators.js @@ -15,8 +15,13 @@ import {StyleSheet, View, Text} from 'react-native'; import * as React from 'react'; const Separator = - (defaultColor, highlightColor) => - ({leadingItem, trailingItem, highlighted, hasBeenHighlighted}) => { + (defaultColor: string, highlightColor: string) => + ({ + leadingItem, + trailingItem, + highlighted, + hasBeenHighlighted, + }: $FlowFixMe) => { const text = `Separator for leading ${leadingItem} and trailing ${trailingItem} has ${ !hasBeenHighlighted ? 'not ' : '' }been pressed`; diff --git a/packages/rn-tester/js/examples/Image/ImageExample.js b/packages/rn-tester/js/examples/Image/ImageExample.js index c1c4ef96bffaa2..eacc26ec27500e 100644 --- a/packages/rn-tester/js/examples/Image/ImageExample.js +++ b/packages/rn-tester/js/examples/Image/ImageExample.js @@ -10,6 +10,8 @@ 'use strict'; +import type {LayoutEvent} from 'react-native/Libraries/Types/CoreEventTypes'; + const React = require('react'); const { @@ -451,7 +453,7 @@ class OnLayoutExample extends React.Component< layoutHandlerMessage: 'No Message', }; - onLayoutHandler = event => { + onLayoutHandler = (event: LayoutEvent) => { this.setState({ width: this.state.width, height: this.state.height, diff --git a/packages/rn-tester/js/examples/KeyboardAvoidingView/KeyboardAvoidingViewExample.js b/packages/rn-tester/js/examples/KeyboardAvoidingView/KeyboardAvoidingViewExample.js index 627b5751f7522c..7a86ed1d872df8 100644 --- a/packages/rn-tester/js/examples/KeyboardAvoidingView/KeyboardAvoidingViewExample.js +++ b/packages/rn-tester/js/examples/KeyboardAvoidingView/KeyboardAvoidingViewExample.js @@ -42,7 +42,11 @@ const TextInputForm = () => { ); }; -const CloseButton = props => { +const CloseButton = ( + props: + | {behavior: any, setModalOpen: any} + | {behavior: string, setModalOpen: any}, +) => { return ( [ + renderBlock = (anim: any | AnimatedValue, dest: any | AnimatedValue) => [ = [ }, ]; -const infoToExample = info => { +const infoToExample = (info: ExampleClass) => { return { title: info.title, description: info.description, diff --git a/packages/rn-tester/js/examples/Pressable/PressableExample.js b/packages/rn-tester/js/examples/Pressable/PressableExample.js index f4629a8bb290c4..b13987f1246586 100644 --- a/packages/rn-tester/js/examples/Pressable/PressableExample.js +++ b/packages/rn-tester/js/examples/Pressable/PressableExample.js @@ -84,7 +84,7 @@ function TextOnPressBox() { function PressableFeedbackEvents() { const [eventLog, setEventLog] = useState([]); - function appendEvent(eventName) { + function appendEvent(eventName: string) { const limit = 6; setEventLog(current => { return [eventName].concat(current.slice(0, limit - 1)); @@ -120,7 +120,7 @@ function PressableFeedbackEvents() { function PressableDelayEvents() { const [eventLog, setEventLog] = useState([]); - function appendEvent(eventName) { + function appendEvent(eventName: string) { const limit = 6; const newEventLog = eventLog.slice(0, limit - 1); newEventLog.unshift(eventName); diff --git a/packages/rn-tester/js/examples/RTL/RTLExample.js b/packages/rn-tester/js/examples/RTL/RTLExample.js index 25415fe0c302ea..f9bb40b4b3a83f 100644 --- a/packages/rn-tester/js/examples/RTL/RTLExample.js +++ b/packages/rn-tester/js/examples/RTL/RTLExample.js @@ -43,7 +43,7 @@ const IMAGE_SIZE = [IMAGE_DIMENSION, IMAGE_DIMENSION]; const IS_RTL = I18nManager.isRTL; -function ListItem(props) { +function ListItem(props: {imageSource: number}) { return ( @@ -127,7 +127,10 @@ const IconsExample = withRTLState(({isRTL, setRTL}) => { ); }); -function AnimationBlock(props) { +function AnimationBlock(props: { + imgStyle: {transform: Array<{scaleX: number} | {translateX: any}>}, + onPress: (e: any) => void, +}) { return ( @@ -144,7 +147,13 @@ type RTLSwitcherComponentState = {| isRTL: boolean, |}; -function withRTLState(Component) { +function withRTLState( + Component: ({ + isRTL: boolean, + setRTL: (isRTL: boolean) => void, + style?: any, + }) => React.Node, +) { return class extends React.Component< {style?: any}, RTLSwitcherComponentState, @@ -157,7 +166,7 @@ function withRTLState(Component) { } render() { - const setRTL = isRTL => this.setState({isRTL: isRTL}); + const setRTL = (isRTL: boolean) => this.setState({isRTL: isRTL}); return ( ); @@ -165,7 +174,12 @@ function withRTLState(Component) { }; } -const RTLToggler = ({isRTL, setRTL}) => { +const RTLToggler = ({ + isRTL, + setRTL, +}: + | {isRTL: any, setRTL: any} + | {isRTL: boolean, setRTL: (isRTL: boolean) => void}) => { if (Platform.OS === 'android') { return {isRTL ? 'RTL' : 'LTR'}; } @@ -528,7 +542,7 @@ const BorderExample = withRTLState(({isRTL, setRTL}) => { ); }); -const directionStyle = isRTL => +const directionStyle = (isRTL: boolean) => Platform.OS !== 'android' ? {direction: isRTL ? 'rtl' : 'ltr'} : null; const styles = StyleSheet.create({ diff --git a/packages/rn-tester/js/examples/SafeAreaView/SafeAreaViewExample.js b/packages/rn-tester/js/examples/SafeAreaView/SafeAreaViewExample.js index ad75dac32b7bbc..12268f6edee774 100644 --- a/packages/rn-tester/js/examples/SafeAreaView/SafeAreaViewExample.js +++ b/packages/rn-tester/js/examples/SafeAreaView/SafeAreaViewExample.js @@ -32,7 +32,7 @@ class SafeAreaViewExample extends React.Component< modalVisible: false, }; - _setModalVisible = visible => { + _setModalVisible = (visible: boolean) => { this.setState({modalVisible: visible}); }; diff --git a/packages/rn-tester/js/examples/ScrollView/ScrollViewExample.js b/packages/rn-tester/js/examples/ScrollView/ScrollViewExample.js index e86361950f21b5..499a077e863560 100644 --- a/packages/rn-tester/js/examples/ScrollView/ScrollViewExample.js +++ b/packages/rn-tester/js/examples/ScrollView/ScrollViewExample.js @@ -732,7 +732,7 @@ const RefreshControlExample = () => { wait(2000).then(() => setRefreshing(false)); }, []); - const wait = timeout => { + const wait = (timeout: number) => { return new Promise(resolve => { setTimeout(resolve, timeout); }); @@ -1253,7 +1253,9 @@ class Item extends React.PureComponent<{| let ITEMS = [...Array(12)].map((_, i) => `Item ${i}`); -const createItemRow = (msg, index) => ; +const createItemRow = (msg: string, index: number) => ( + +); const Button = (props: { active?: boolean, diff --git a/packages/rn-tester/js/examples/SectionList/SectionList-onEndReached.js b/packages/rn-tester/js/examples/SectionList/SectionList-onEndReached.js index 04c5dc6ea46c80..498f0c4e8d98aa 100644 --- a/packages/rn-tester/js/examples/SectionList/SectionList-onEndReached.js +++ b/packages/rn-tester/js/examples/SectionList/SectionList-onEndReached.js @@ -14,7 +14,8 @@ import * as React from 'react'; export function SectionList_onEndReached(): React.Node { const [output, setOutput] = React.useState(''); const exampleProps = { - onEndReached: info => setOutput('onEndReached'), + onEndReached: (info: {distanceFromEnd: number, ...}) => + setOutput('onEndReached'), onEndReachedThreshold: 0, }; const ref = React.useRef(null); diff --git a/packages/rn-tester/js/examples/SectionList/SectionList-onViewableItemsChanged.js b/packages/rn-tester/js/examples/SectionList/SectionList-onViewableItemsChanged.js index ff40342e58751a..f93996530880ba 100644 --- a/packages/rn-tester/js/examples/SectionList/SectionList-onViewableItemsChanged.js +++ b/packages/rn-tester/js/examples/SectionList/SectionList-onViewableItemsChanged.js @@ -8,6 +8,7 @@ * @flow */ +import type {ViewToken} from 'react-native/Libraries/Lists/ViewabilityHelper'; import SectionListBaseExample from './SectionListBaseExample'; import {View, StyleSheet, SectionList} from 'react-native'; import * as React from 'react'; @@ -30,7 +31,11 @@ export function SectionList_onViewableItemsChanged(props: { const {viewabilityConfig, offScreen, horizontal, useScrollRefScroll} = props; const [output, setOutput] = React.useState(''); const exampleProps = { - onViewableItemsChanged: info => + onViewableItemsChanged: (info: { + changed: Array, + viewableItems: Array, + ... + }) => setOutput( info.viewableItems .filter(viewToken => viewToken.index != null && viewToken.isViewable) diff --git a/packages/rn-tester/js/examples/SectionList/SectionList-scrollable.js b/packages/rn-tester/js/examples/SectionList/SectionList-scrollable.js index 88fda4e8171869..58452b7badc0a9 100644 --- a/packages/rn-tester/js/examples/SectionList/SectionList-scrollable.js +++ b/packages/rn-tester/js/examples/SectionList/SectionList-scrollable.js @@ -9,6 +9,7 @@ */ 'use strict'; +import type {Item} from '../../components/ListExampleShared'; const RNTesterPage = require('../../components/RNTesterPage'); const React = require('react'); @@ -108,7 +109,7 @@ const EmptySectionList = () => ( ); const renderItemComponent = - setItemState => + (setItemState: (item: Item) => void) => ({item, separators}) => { if (isNaN(item.key)) { return; @@ -164,7 +165,7 @@ export function SectionList_scrollable(Props: { const [data, setData] = React.useState(genItemData(1000)); const filterRegex = new RegExp(String(filterText), 'i'); - const filter = item => + const filter = (item: Item) => filterRegex.test(item.text) || filterRegex.test(item.title); const filteredData = data.filter(filter); const filteredSectionData = [...CONSTANT_SECTION_EXAMPLES]; @@ -181,7 +182,7 @@ export function SectionList_scrollable(Props: { startIndex = ii; } - const setItemPress = item => { + const setItemPress = (item: Item) => { if (isNaN(item.key)) { return; } @@ -190,7 +191,7 @@ export function SectionList_scrollable(Props: { }; const ref = React.useRef>(null); - const scrollToLocation = (sectionIndex, itemIndex) => { + const scrollToLocation = (sectionIndex: number, itemIndex: number) => { // $FlowFixMe[method-unbinding] added when improving typing for this parameters if (ref != null && ref.current?.scrollToLocation != null) { ref.current.scrollToLocation({sectionIndex, itemIndex}); diff --git a/packages/rn-tester/js/examples/SectionList/SectionList-withSeparators.js b/packages/rn-tester/js/examples/SectionList/SectionList-withSeparators.js index ec93af1f63b991..9042f205d334e8 100644 --- a/packages/rn-tester/js/examples/SectionList/SectionList-withSeparators.js +++ b/packages/rn-tester/js/examples/SectionList/SectionList-withSeparators.js @@ -13,8 +13,8 @@ import {View, Text, StyleSheet} from 'react-native'; import * as React from 'react'; const Separator = - (defaultColor, highlightColor, isSectionSeparator) => - ({leadingItem, trailingItem, highlighted, hasBeenHighlighted}) => { + (defaultColor: string, highlightColor: string, isSectionSeparator: boolean) => + ({leadingItem, trailingItem, highlighted, hasBeenHighlighted}: any) => { const text = `${ isSectionSeparator ? 'Section ' : '' }separator for leading ${leadingItem} and trailing ${trailingItem} has ${ diff --git a/packages/rn-tester/js/examples/SwipeableCardExample/SwipeableCardExample.js b/packages/rn-tester/js/examples/SwipeableCardExample/SwipeableCardExample.js index fe7c947e9094d0..41ff93ac454bc0 100644 --- a/packages/rn-tester/js/examples/SwipeableCardExample/SwipeableCardExample.js +++ b/packages/rn-tester/js/examples/SwipeableCardExample/SwipeableCardExample.js @@ -8,6 +8,8 @@ * @format */ +import type {RenderItemProps} from 'react-native/Libraries/Lists/VirtualizedList'; + import * as React from 'react'; import { Animated, @@ -49,7 +51,7 @@ function SwipeableCardExample() { const incrementCurrent = () => setCurrentIndex(currentIndex + 1); - const getCardColor = index => cardColors[index % cardColors.length]; + const getCardColor = (index: number) => cardColors[index % cardColors.length]; /* * The cards try to reuse the views. Instead of always rebuilding the current card on top @@ -140,7 +142,7 @@ function SwipeableCard(props: { const cardData = Array(5); function Card(props: {color: string}) { - const renderItem = ({item, index}) => ( + const renderItem = ({item, index}: RenderItemProps<$FlowFixMe>) => ( ); diff --git a/packages/rn-tester/js/examples/TextInput/TextInputExample.ios.js b/packages/rn-tester/js/examples/TextInput/TextInputExample.ios.js index be0a6f60357045..5d27d97eccbc21 100644 --- a/packages/rn-tester/js/examples/TextInput/TextInputExample.ios.js +++ b/packages/rn-tester/js/examples/TextInput/TextInputExample.ios.js @@ -46,7 +46,7 @@ class TextInputAccessoryViewChangeTextExample extends React.Component< {...}, {text: string}, > { - constructor(props) { + constructor(props: void | {...}) { super(props); this.state = {text: 'Placeholder Text'}; } @@ -79,7 +79,7 @@ class TextInputAccessoryViewChangeKeyboardExample extends React.Component< {...}, {keyboardType: string, text: string}, > { - constructor(props) { + constructor(props: void | {...}) { super(props); this.state = {text: '', keyboardType: 'default'}; } @@ -121,7 +121,7 @@ class TextInputAccessoryViewDefaultDoneButtonExample extends React.Component< |}>, {text: string}, > { - constructor(props) { + constructor(props: void | $ReadOnly<{keyboardType: KeyboardType}>) { super(props); this.state = {text: ''}; } @@ -140,7 +140,7 @@ class TextInputAccessoryViewDefaultDoneButtonExample extends React.Component< } class RewriteExampleKana extends React.Component<$FlowFixMeProps, any> { - constructor(props) { + constructor(props: any | void) { super(props); this.state = {text: ''}; } @@ -161,7 +161,7 @@ class RewriteExampleKana extends React.Component<$FlowFixMeProps, any> { } class SecureEntryExample extends React.Component<$FlowFixMeProps, any> { - constructor(props) { + constructor(props: any | void) { super(props); this.state = { text: '', @@ -209,7 +209,7 @@ class AutogrowingTextInputExample extends React.Component< $FlowFixMeProps, $FlowFixMeState, > { - constructor(props) { + constructor(props: any | void) { super(props); this.state = { @@ -223,7 +223,7 @@ class AutogrowingTextInputExample extends React.Component< }; } - UNSAFE_componentWillReceiveProps(props) { + UNSAFE_componentWillReceiveProps(props: any) { this.setState({ multiline: props.multiline, }); diff --git a/packages/rn-tester/js/examples/TextInput/TextInputSharedExamples.js b/packages/rn-tester/js/examples/TextInput/TextInputSharedExamples.js index 19e758f2a7dd5a..24874bf2dac977 100644 --- a/packages/rn-tester/js/examples/TextInput/TextInputSharedExamples.js +++ b/packages/rn-tester/js/examples/TextInput/TextInputSharedExamples.js @@ -88,7 +88,7 @@ class WithLabel extends React.Component<$FlowFixMeProps> { } class RewriteExample extends React.Component<$FlowFixMeProps, any> { - constructor(props) { + constructor(props: any | void) { super(props); this.state = {text: ''}; } @@ -122,7 +122,7 @@ class RewriteExampleInvalidCharacters extends React.Component< $FlowFixMeProps, any, > { - constructor(props) { + constructor(props: any | void) { super(props); this.state = {text: ''}; } @@ -150,7 +150,7 @@ class RewriteInvalidCharactersAndClearExample extends React.Component< > { inputRef: ?React.ElementRef = null; - constructor(props) { + constructor(props: any | void) { super(props); this.state = {text: ''}; } @@ -248,7 +248,7 @@ class TextEventsExample extends React.Component<{...}, $FlowFixMeState> { prev3Text: '', }; - updateText = text => { + updateText = (text: string) => { this.setState(state => { return { curText: text, @@ -305,7 +305,7 @@ class TokenizedTextExample extends React.Component< $FlowFixMeProps, $FlowFixMeState, > { - constructor(props) { + constructor(props: any | void) { super(props); this.state = {text: 'Hello #World'}; } @@ -396,7 +396,7 @@ class SelectionExample extends React.Component< return Math.round(Math.random() * length); } - select(start, end) { + select(start: number, end: number) { this._textInput?.focus(); this.setState({selection: {start, end}}); if (this.props.imperative) { @@ -412,7 +412,7 @@ class SelectionExample extends React.Component< this.select(...positions); } - placeAt(position) { + placeAt(position: number) { this.select(position, position); } diff --git a/packages/rn-tester/js/examples/Timer/TimerExample.js b/packages/rn-tester/js/examples/Timer/TimerExample.js index e06b1cd227fcff..2a4b75849fc46c 100644 --- a/packages/rn-tester/js/examples/Timer/TimerExample.js +++ b/packages/rn-tester/js/examples/Timer/TimerExample.js @@ -15,7 +15,7 @@ const React = require('react'); const {Alert, Platform, ToastAndroid, Text, View} = require('react-native'); -function burnCPU(milliseconds) { +function burnCPU(milliseconds: number) { const start = global.performance.now(); while (global.performance.now() < start + milliseconds) {} } @@ -117,7 +117,11 @@ class RequestIdleCallbackTester extends React.Component< this._idleTimer = null; } - const handler = deadline => { + const handler = (deadline: { + didTimeout: boolean, + timeRemaining: () => number, + ... + }) => { while (deadline.timeRemaining() > 5) { burnCPU(5); this.setState({ diff --git a/packages/rn-tester/js/examples/Touchable/TouchableExample.js b/packages/rn-tester/js/examples/Touchable/TouchableExample.js index eed3b4a53a21b3..a4df8b52ada0bd 100644 --- a/packages/rn-tester/js/examples/Touchable/TouchableExample.js +++ b/packages/rn-tester/js/examples/Touchable/TouchableExample.js @@ -181,7 +181,7 @@ class TouchableFeedbackEvents extends React.Component<{...}, $FlowFixMeState> { ); } - _appendEvent = eventName => { + _appendEvent = (eventName: string) => { const limit = 6; const eventLog = this.state.eventLog.slice(0, limit - 1); eventLog.unshift(eventName); @@ -222,7 +222,7 @@ class TouchableDelayEvents extends React.Component<{...}, $FlowFixMeState> { ); } - _appendEvent = eventName => { + _appendEvent = (eventName: string) => { const limit = 6; const eventLog = this.state.eventLog.slice(0, limit - 1); eventLog.unshift(eventName); diff --git a/packages/rn-tester/js/examples/TurboModule/SampleTurboModuleExample.js b/packages/rn-tester/js/examples/TurboModule/SampleTurboModuleExample.js index 96c91a34f11449..09e14a94e247f2 100644 --- a/packages/rn-tester/js/examples/TurboModule/SampleTurboModuleExample.js +++ b/packages/rn-tester/js/examples/TurboModule/SampleTurboModuleExample.js @@ -73,7 +73,33 @@ class SampleTurboModuleExample extends React.Component<{||}, State> { NativeSampleTurboModule.getValue(5, 'test', {a: 1, b: 'foo'}), }; - _setResult(name, result) { + _setResult( + name: + | string + | 'callback' + | 'getArray' + | 'getBool' + | 'getConstants' + | 'getNumber' + | 'getObject' + | 'getRootTag' + | 'getString' + | 'getUnsafeObject' + | 'getValue' + | 'promise' + | 'rejectPromise' + | 'voidFunc', + result: + | $FlowFixMe + | void + | RootTag + | Promise + | number + | string + | boolean + | {const1: boolean, const2: number, const3: string} + | Array<$FlowFixMe>, + ) { this.setState(({testResults}) => ({ /* $FlowFixMe[cannot-spread-indexer] (>=0.122.0 site=react_native_fb) * This comment suppresses an error found when Flow v0.122.0 was @@ -88,7 +114,22 @@ class SampleTurboModuleExample extends React.Component<{||}, State> { })); } - _renderResult(name) { + _renderResult( + name: + | 'callback' + | 'getArray' + | 'getBool' + | 'getConstants' + | 'getNumber' + | 'getObject' + | 'getRootTag' + | 'getString' + | 'getUnsafeObject' + | 'getValue' + | 'promise' + | 'rejectPromise' + | 'voidFunc', + ) { const result = this.state.testResults[name] || {}; return (