Transform all remaining utility types (#55178)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/55178

We are transforming the following utility types to be more consistent with typescript and better AI integration:

* `$NonMaybeType` -> `NonNullable`
* `$ReadOnly` -> `Readonly`
* `$ReadOnlyArray` -> `ReadonlyArray`
* `$ReadOnlyMap` -> `ReadonlyMap`
* `$ReadOnlySet` -> `ReadonlySet`
* `$Keys` -> `keyof`
* `$Values` -> `Values`
* `mixed` -> `unknown`

See details in https://fb.workplace.com/groups/flowlang/permalink/1837907750148213/.

drop-conflicts

Command:

`js1 flow-runner codemod flow/transformUtilityType --format-files=false --legacy-type='ALL'`

Reviewed By: SamChou19815

Differential Revision: D90728908

fbshipit-source-id: a8a1a06eb274cc32b12e893679aa92034eb962c4
This commit is contained in:
Marco Wang authored and meta-codesync[bot] committed 2026-01-15 16:02:51 -08:00
1 parent 5ab418460b
commit cd3a9c55c1
30 files changed
+82 -88

No files matched your search

+5 -5
View File
@@ -556,24 +556,24 @@ declare module '@babel/traverse' {
* Check whether we have the input `key`. If the `key` references an array then we check
* if the array has any items, otherwise we just check if it's falsy.
*/
has(key: $Keys<TNode>): boolean;
has(key: keyof TNode): boolean;
isStatic(): boolean;
/**
* Alias of `has`.
*/
is(key: $Keys<TNode>): boolean;
is(key: keyof TNode): boolean;
/**
* Opposite of `has`.
*/
isnt(key: $Keys<TNode>): boolean;
isnt(key: keyof TNode): boolean;
/**
* Check whether the path node `key` strict equals `value`.
*/
equals(key: $Keys<TNode>, value: any): boolean;
equals(key: keyof TNode, value: any): boolean;
/**
* Check the type against our stored internal type of the node. This is handy when a node has
@@ -724,7 +724,7 @@ declare module '@babel/traverse' {
getAllPrevSiblings(): Array<NodePath<>>;
get<TKey: $Keys<TNode>>(
get<TKey: keyof TNode>(
key: TKey,
context?: boolean | TraversalContext,
): TNode[TKey] extends BabelNode ? NodePath<> : Array<NodePath<>>;
+2 -2
View File
@@ -2193,10 +2193,10 @@ declare module 'rxjs/operators' {
): rxjs$MonoTypeOperatorFunction<T>;
declare export function distinctUntilKeyChanged<T>(
key: $Keys<T>,
key: keyof T,
): rxjs$MonoTypeOperatorFunction<T>;
declare export function distinctUntilKeyChanged<T, K: $Keys<T>>(
declare export function distinctUntilKeyChanged<T, K: keyof T>(
key: K,
compare: (x: unknown, y: unknown) => boolean,
): rxjs$MonoTypeOperatorFunction<T>;
@@ -480,7 +480,7 @@ export default class Device {
/**
* Returns `true` if a page supports the given target capability flag.
*/
#pageHasCapability(page: Page, flag: $Keys<TargetCapabilityFlags>): boolean {
#pageHasCapability(page: Page, flag: keyof TargetCapabilityFlags): boolean {
return page.capabilities[flag] === true;
}
@@ -12,18 +12,18 @@ import type {JSONSerializable} from '../types';
import type {Commands, Events} from './protocol';
// Note: A CDP event is a JSON-RPC notification with no `id` member.
export type CDPEvent<TEvent: $Keys<Events> = 'unknown'> = {
export type CDPEvent<TEvent: keyof Events = 'unknown'> = {
method: TEvent,
params: Events[TEvent],
};
export type CDPRequest<TCommand: $Keys<Commands> = 'unknown'> = {
export type CDPRequest<TCommand: keyof Commands = 'unknown'> = {
method: TCommand,
params: Commands[TCommand]['paramsType'],
id: number,
};
export type CDPResponse<TCommand: $Keys<Commands> = 'unknown'> =
export type CDPResponse<TCommand: keyof Commands = 'unknown'> =
| {
result: Commands[TCommand]['resultType'],
id: number,
@@ -65,9 +65,9 @@ type PassThroughProps = Readonly<{
passthroughAnimatedPropExplicitValues?: ViewProps | null,
}>;
type LooseOmit<O: interface {}, K: $Keys<$FlowFixMe>> = Pick<
type LooseOmit<O: interface {}, K: keyof $FlowFixMe> = Pick<
O,
Exclude<$Keys<O>, K>,
Exclude<keyof O, K>,
>;
export type AnimatedProps<Props: {...}> = LooseOmit<
+1 -1
View File
@@ -42,7 +42,7 @@ type AppStateEventDefinitions = {
focus: [],
};
export type AppStateEvent = $Keys<AppStateEventDefinitions>;
export type AppStateEvent = keyof AppStateEventDefinitions;
type NativeAppStateEventDefinitions = {
appStateDidChange: [{app_state: AppStateStatus}],
@@ -49,30 +49,28 @@ type AccessibilityEventTypes =
| 'windowStateChange';
// Mapping of public event names to platform-specific event names.
const EventNames: Map<
$Keys<AccessibilityEventDefinitions>,
string,
> = Platform.OS === 'android'
? new Map([
['change', 'touchExplorationDidChange'],
['reduceMotionChanged', 'reduceMotionDidChange'],
['highTextContrastChanged', 'highTextContrastDidChange'],
['screenReaderChanged', 'touchExplorationDidChange'],
['accessibilityServiceChanged', 'accessibilityServiceDidChange'],
['invertColorsChanged', 'invertColorDidChange'],
['grayscaleChanged', 'grayscaleModeDidChange'],
])
: new Map([
['announcementFinished', 'announcementFinished'],
['boldTextChanged', 'boldTextChanged'],
['change', 'screenReaderChanged'],
['grayscaleChanged', 'grayscaleChanged'],
['invertColorsChanged', 'invertColorsChanged'],
['reduceMotionChanged', 'reduceMotionChanged'],
['reduceTransparencyChanged', 'reduceTransparencyChanged'],
['screenReaderChanged', 'screenReaderChanged'],
['darkerSystemColorsChanged', 'darkerSystemColorsChanged'],
]);
const EventNames: Map<keyof AccessibilityEventDefinitions, string> =
Platform.OS === 'android'
? new Map([
['change', 'touchExplorationDidChange'],
['reduceMotionChanged', 'reduceMotionDidChange'],
['highTextContrastChanged', 'highTextContrastDidChange'],
['screenReaderChanged', 'touchExplorationDidChange'],
['accessibilityServiceChanged', 'accessibilityServiceDidChange'],
['invertColorsChanged', 'invertColorDidChange'],
['grayscaleChanged', 'grayscaleModeDidChange'],
])
: new Map([
['announcementFinished', 'announcementFinished'],
['boldTextChanged', 'boldTextChanged'],
['change', 'screenReaderChanged'],
['grayscaleChanged', 'grayscaleChanged'],
['invertColorsChanged', 'invertColorsChanged'],
['reduceMotionChanged', 'reduceMotionChanged'],
['reduceTransparencyChanged', 'reduceTransparencyChanged'],
['screenReaderChanged', 'screenReaderChanged'],
['darkerSystemColorsChanged', 'darkerSystemColorsChanged'],
]);
/**
* Sometimes it's useful to know whether or not the device has a screen reader
@@ -426,7 +424,7 @@ const AccessibilityInfo = {
*
* See https://reactnative.dev/docs/accessibilityinfo#addeventlistener
*/
addEventListener<K: $Keys<AccessibilityEventDefinitions>>(
addEventListener<K: keyof AccessibilityEventDefinitions>(
eventName: K,
// $FlowFixMe[incompatible-type] - Flow bug with unions and generics (T128099423)
handler: (...AccessibilityEventDefinitions[K]) => void,
@@ -16,7 +16,7 @@ import dismissKeyboard from '../../Utilities/dismissKeyboard';
import Platform from '../../Utilities/Platform';
import NativeKeyboardObserver from './NativeKeyboardObserver';
export type KeyboardEventName = $Keys<KeyboardEventDefinitions>;
export type KeyboardEventName = keyof KeyboardEventDefinitions;
export type KeyboardEventEasing =
| 'easeIn'
@@ -146,7 +146,7 @@ class KeyboardImpl {
*
* @param {function} callback function to be called when the event fires.
*/
addListener<K: $Keys<KeyboardEventDefinitions>>(
addListener<K: keyof KeyboardEventDefinitions>(
eventType: K,
listener: (...KeyboardEventDefinitions[K]) => unknown,
context?: unknown,
@@ -159,7 +159,7 @@ class KeyboardImpl {
*
* @param {string} eventType The native event string listeners are watching which will be removed.
*/
removeAllListeners<K: $Keys<KeyboardEventDefinitions>>(eventType: ?K): void {
removeAllListeners<K: keyof KeyboardEventDefinitions>(eventType: ?K): void {
this._emitter.removeAllListeners(eventType);
}
@@ -21,7 +21,7 @@ export type {ProgressBarAndroidProps};
// of ProgressBarAndroidProps. TS's Omit does not distribute over unions, so
// we define our own version which does. This does not affect Flow.
// $FlowExpectedError[unclear-type]
type Omit<T, K> = T extends any ? Pick<T, Exclude<$Keys<T>, K>> : T;
type Omit<T, K> = T extends any ? Pick<T, Exclude<keyof T, K>> : T;
/**
* ProgressBarAndroid has been extracted from react-native core and will be removed in a future release.
@@ -20,7 +20,7 @@ import * as React from 'react';
/**
* Status bar style
*/
export type StatusBarStyle = $Keys<{
export type StatusBarStyle = keyof {
/**
* Default status bar style (dark for iOS, light for Android)
*/
@@ -34,12 +34,12 @@ export type StatusBarStyle = $Keys<{
*/
'dark-content': string,
...
}>;
};
/**
* Status bar animation
*/
export type StatusBarAnimation = $Keys<{
export type StatusBarAnimation = keyof {
/**
* No animation
*/
@@ -53,7 +53,7 @@ export type StatusBarAnimation = $Keys<{
*/
slide: string,
...
}>;
};
export type StatusBarPropsAndroid = Readonly<{
/**
@@ -83,7 +83,7 @@ export default class NativeEventEmitter<
}
}
addListener<TEvent: $Keys<TEventToArgsMap>>(
addListener<TEvent: keyof TEventToArgsMap>(
eventType: TEvent,
listener: (...args: TEventToArgsMap[TEvent]) => unknown,
context?: unknown,
@@ -107,7 +107,7 @@ export default class NativeEventEmitter<
};
}
emit<TEvent: $Keys<TEventToArgsMap>>(
emit<TEvent: keyof TEventToArgsMap>(
eventType: TEvent,
...args: TEventToArgsMap[TEvent]
): void {
@@ -116,9 +116,7 @@ export default class NativeEventEmitter<
RCTDeviceEventEmitter.emit(eventType, ...args);
}
removeAllListeners<TEvent: $Keys<TEventToArgsMap>>(
eventType?: ?TEvent,
): void {
removeAllListeners<TEvent: keyof TEventToArgsMap>(eventType?: ?TEvent): void {
invariant(
eventType != null,
'`NativeEventEmitter.removeAllListener()` requires a non-null argument.',
@@ -127,7 +125,7 @@ export default class NativeEventEmitter<
RCTDeviceEventEmitter.removeAllListeners(eventType);
}
listenerCount<TEvent: $Keys<TEventToArgsMap>>(eventType: TEvent): number {
listenerCount<TEvent: keyof TEventToArgsMap>(eventType: TEvent): number {
return RCTDeviceEventEmitter.listenerCount(eventType);
}
}
@@ -25,7 +25,7 @@ type RCTDeviceEventDefinitions = {[name: string]: Array<any>};
*/
class RCTDeviceEventEmitterImpl extends EventEmitter<RCTDeviceEventDefinitions> {
// Add systrace to RCTDeviceEventEmitter.emit method for debugging
emit<TEvent: $Keys<RCTDeviceEventDefinitions>>(
emit<TEvent: keyof RCTDeviceEventDefinitions>(
eventType: TEvent,
...args: RCTDeviceEventDefinitions[TEvent]
): void {
@@ -22,7 +22,7 @@ export default class NativeEventEmitter<
TEventToArgsMap: Readonly<Record<string, ReadonlyArray<unknown>>>,
> implements IEventEmitter<TEventToArgsMap>
{
addListener<TEvent: $Keys<TEventToArgsMap>>(
addListener<TEvent: keyof TEventToArgsMap>(
eventType: TEvent,
listener: (...args: TEventToArgsMap[TEvent]) => unknown,
context?: unknown,
@@ -30,20 +30,18 @@ export default class NativeEventEmitter<
return RCTDeviceEventEmitter.addListener(eventType, listener, context);
}
emit<TEvent: $Keys<TEventToArgsMap>>(
emit<TEvent: keyof TEventToArgsMap>(
eventType: TEvent,
...args: TEventToArgsMap[TEvent]
): void {
RCTDeviceEventEmitter.emit(eventType, ...args);
}
removeAllListeners<TEvent: $Keys<TEventToArgsMap>>(
eventType?: ?TEvent,
): void {
removeAllListeners<TEvent: keyof TEventToArgsMap>(eventType?: ?TEvent): void {
RCTDeviceEventEmitter.removeAllListeners(eventType);
}
listenerCount<TEvent: $Keys<TEventToArgsMap>>(eventType: TEvent): number {
listenerCount<TEvent: keyof TEventToArgsMap>(eventType: TEvent): number {
return RCTDeviceEventEmitter.listenerCount(eventType);
}
}
+1 -1
View File
@@ -32,7 +32,7 @@ class LinkingImpl extends NativeEventEmitter<LinkingEventDefinitions> {
*
* See https://reactnative.dev/docs/linking#addeventlistener
*/
addEventListener<K: $Keys<LinkingEventDefinitions>>(
addEventListener<K: keyof LinkingEventDefinitions>(
eventType: K,
listener: (...LinkingEventDefinitions[K]) => unknown,
): EventSubscription {
@@ -48,7 +48,7 @@ const emitter = new NativeEventEmitter<$FlowFixMe>(
* requestId to each network request that can be used to abort that request later on.
*/
const RCTNetworking = {
addListener<K: $Keys<RCTNetworkingEventDefinitions>>(
addListener<K: keyof RCTNetworkingEventDefinitions>(
eventType: K,
listener: (...RCTNetworkingEventDefinitions[K]) => unknown,
context?: unknown,
@@ -18,7 +18,7 @@ import {type RCTNetworkingEventDefinitions} from './RCTNetworkingEventDefinition
import {type NativeResponseType} from './XMLHttpRequest';
const RCTNetworking = {
addListener<K: $Keys<RCTNetworkingEventDefinitions>>(
addListener<K: keyof RCTNetworkingEventDefinitions>(
eventType: K,
listener: (...RCTNetworkingEventDefinitions[K]) => unknown,
context?: unknown,
@@ -16,7 +16,7 @@ import type {RCTNetworkingEventDefinitions} from './RCTNetworkingEventDefinition
import type {NativeResponseType} from './XMLHttpRequest';
declare const RCTNetworking: interface {
addListener<K: $Keys<RCTNetworkingEventDefinitions>>(
addListener<K: keyof RCTNetworkingEventDefinitions>(
eventType: K,
// $FlowFixMe[invalid-computed-prop]
listener: (...RCTNetworkingEventDefinitions[K]) => unknown,
@@ -89,7 +89,7 @@ export type FetchResult = {
/**
* An event emitted by PushNotificationIOS.
*/
export type PushNotificationEventName = $Keys<{
export type PushNotificationEventName = keyof {
/**
* Fired when a remote notification is received. The handler will be invoked
* with an instance of `PushNotificationIOS`. This will handle notifications
@@ -116,7 +116,7 @@ export type PushNotificationEventName = $Keys<{
*/
registrationError: string,
...
}>;
};
export interface PushNotification {
/**
@@ -37,11 +37,11 @@ function getPaperRenderer(): ReactNativeType {
return cachedPaperRenderer;
}
const getMethod: (<MethodName: $Keys<ReactFabricType>>(
const getMethod: (<MethodName: keyof ReactFabricType>(
() => ReactFabricType,
MethodName,
) => ReactFabricType[MethodName]) &
(<MethodName: $Keys<ReactNativeType>>(
(<MethodName: keyof ReactNativeType>(
() => ReactNativeType,
MethodName,
) => ReactNativeType[MethodName]) = (getRenderer, methodName) => {
@@ -59,13 +59,13 @@ const getMethod: (<MethodName: $Keys<ReactFabricType>>(
};
};
function getFabricMethod<MethodName: $Keys<ReactFabricType>>(
function getFabricMethod<MethodName: keyof ReactFabricType>(
methodName: MethodName,
): ReactFabricType[MethodName] {
return getMethod(getFabricRenderer, methodName);
}
function getPaperMethod<MethodName: $Keys<ReactNativeType>>(
function getPaperMethod<MethodName: keyof ReactNativeType>(
methodName: MethodName,
): ReactNativeType[MethodName] {
return getMethod(getPaperRenderer, methodName);
+1 -1
View File
@@ -118,7 +118,7 @@ export type DangerouslyImpreciseStyleProp =
* This will correctly give you the type 'absolute' | 'relative'
*/
export type TypeForStyleKey<
+key: $Keys<____DangerouslyImpreciseStyle_Internal>,
+key: keyof ____DangerouslyImpreciseStyle_Internal,
> = ____DangerouslyImpreciseStyle_Internal[key];
/**
@@ -119,7 +119,7 @@ export type DangerouslyImpreciseStyleProp =
* This will correctly give you the type 'absolute' | 'relative'
*/
export type TypeForStyleKey<
+key: $Keys<____DangerouslyImpreciseStyle_Internal>,
+key: keyof ____DangerouslyImpreciseStyle_Internal,
> = ____DangerouslyImpreciseStyle_Internal[key];
/**
@@ -13,10 +13,10 @@ import type AnimatedNode from '../../Animated/nodes/AnimatedNode';
// Helper types to enforce that a single key is used in a transform object
// after generating a TypeScript definition file from the Flow types.
// $FlowExpectedError[unclear-type]
type KeysOfUnion<T> = T extends any ? $Keys<T> : empty;
type KeysOfUnion<T> = T extends any ? keyof T : empty;
// $FlowExpectedError[unclear-type]
type ValueOfUnion<T, K> = T extends any
? K extends $Keys<T>
? K extends keyof T
? T[K]
: empty
: empty;
@@ -34,12 +34,12 @@ export type ReactDevToolsAgentEvents = {
export type ReactDevToolsAgent = {
selectNode(node: unknown): void,
stopInspectingNative(value: boolean): void,
addListener<Event: $Keys<ReactDevToolsAgentEvents>>(
addListener<Event: keyof ReactDevToolsAgentEvents>(
event: Event,
listener: (...ReactDevToolsAgentEvents[Event]) => void,
): void,
removeListener(
event: $Keys<ReactDevToolsAgentEvents>,
event: keyof ReactDevToolsAgentEvents,
listener: () => void,
): void,
};
@@ -15,9 +15,9 @@ type NativeCommandsOptions<T = string> = Readonly<{
}>;
function codegenNativeCommands<T: interface {}>(
options: NativeCommandsOptions<$Keys<T>>,
options: NativeCommandsOptions<keyof T>,
): T {
const commandObj: {[$Keys<T>]: (...ReadonlyArray<unknown>) => void} = {};
const commandObj: {[keyof T]: (...ReadonlyArray<unknown>) => void} = {};
options.supportedCommands.forEach(command => {
// $FlowFixMe[missing-local-annot]
@@ -38,7 +38,7 @@ const MEMORY_LIMITS_KB = {
},
};
function limitFor(scenario: $Keys<typeof MEMORY_LIMITS_KB>): number {
function limitFor(scenario: keyof typeof MEMORY_LIMITS_KB): number {
return MEMORY_LIMITS_KB[scenario][__DEV__ ? 'dev' : 'opt'];
}
@@ -118,7 +118,7 @@ let root: Root;
function getAccessibilityProp(
content: React.MixedElement,
name: $Keys<AccessibilityProps>,
name: keyof AccessibilityProps,
) {
Fantom.runTask(() => {
root.render(content);
@@ -128,7 +128,7 @@ function getAccessibilityProp(
function getAccessibilityProps(
content: React.MixedElement,
names: ReadonlyArray<$Keys<AccessibilityProps>>,
names: ReadonlyArray<keyof AccessibilityProps>,
) {
Fantom.runTask(() => {
root.render(content);
@@ -52,7 +52,7 @@ function createGetter<T: boolean | number | string>(
}
export function createJavaScriptFlagGetter<
K: $Keys<ReactNativeFeatureFlagsJsOnly>,
K: keyof ReactNativeFeatureFlagsJsOnly,
>(
configName: K,
defaultValue: ReturnType<ReactNativeFeatureFlagsJsOnly[K]>,
@@ -69,7 +69,7 @@ export function createJavaScriptFlagGetter<
type NativeFeatureFlags = NonNullable<typeof NativeReactNativeFeatureFlags>;
export function createNativeFlagGetter<K: $Keys<NativeFeatureFlags>>(
export function createNativeFlagGetter<K: keyof NativeFeatureFlags>(
configName: K,
defaultValue: ReturnType<NonNullable<NativeFeatureFlags[K]>>,
skipUnavailableNativeModuleError: boolean = false,
@@ -55,7 +55,7 @@ const getUpdatedRecentlyUsed = ({
export const RNTesterNavigationReducer = (
state: RNTesterNavigationState,
action: {type: $Keys<typeof RNTesterNavigationActionsType>, data?: any},
action: {type: keyof typeof RNTesterNavigationActionsType, data?: any},
): RNTesterNavigationState => {
const {
data: {
@@ -32,7 +32,7 @@ export default class StateSafePureComponent<
}
// $FlowFixMe[incompatible-type]
setState<K: $Keys<State>>(
setState<K: keyof State>(
partialState: ?(Pick<State, K> | ((State, Props) => ?Pick<State, K>)),
callback?: () => unknown,
): void {
+3 -3
View File
@@ -70,7 +70,7 @@ const defaultBuildOptions = {
};
function getBuildOptions(
packageName: $Keys<BuildConfig['packages']>,
packageName: keyof BuildConfig['packages'],
): Required<BuildOptions> {
return {
...defaultBuildOptions,
@@ -79,7 +79,7 @@ function getBuildOptions(
}
function getBabelConfig(
packageName: $Keys<BuildConfig['packages']>,
packageName: keyof BuildConfig['packages'],
): BabelCoreOptions {
const {target} = getBuildOptions(packageName);
@@ -90,7 +90,7 @@ function getBabelConfig(
}
function getTypeScriptCompilerOptions(
packageName: $Keys<BuildConfig['packages']>,
packageName: keyof BuildConfig['packages'],
): Object {
const {target} = getBuildOptions(packageName);