Prune no-op Omit keys from generated types (#56824)

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

Update the `simplifyTypes` transform (Flow → TS generation) to prune non-overlapping keys from `Omit<>` helpers in TypeScript `interface` unions.

This greatly reduces API snapshot churn/inflation in the next two diffs, which convert a number of `type` declarations (trivial unions) to `interface` (`Omit<>` required for correct union).

#### In detail

`flow-api-translator` emits `Omit<ParentType, keys>` to faithfully translate Flow's object spread override semantics to TypeScript.

```
// Flow
type Base = {x: string, y: number};
type Child = {...Base, x: boolean}; // Later properties in an object spread override earlier ones

// TypeScript
type Base = {x: string; y: number};
type Child = Omit<Base, "x" | "y"> & {x: boolean};  // Later properties in an object spread *merge*, rather than override. So we must use Omit<> for matched keys.
```

For `interface` type unions with overlapping keys, this can result in a number of unnecessary lines in the API snapshot, with little/no human readable value.

This diff extends existing `Omit<>` handling by `simplifyTypes` to recursively resolve all property keys reachable from a type, and prune keys that don't exist on the parent type.

```
// TypeScript
type Child = Omit<Base, "x"> & {x: boolean};  // Only "x" matched - strip `| "y"`
type ChildTwo = Base & {z: string};  // No property collision - strip entire `Omit<>`
```

- See changes to `ReactNativeApi.d.ts`, [P2325468482](https://www.internalfb.com/phabricator/paste/view/P2325468482?view=diff) for examples.
- **Decision point**: This diff opts to preserve correctness in TS — even though the snapshot isn't/isn't intended to be read directly/programatically, vs the conciseness tradeoff if we dropped all `Omit<>`s (human readable but ambiguous to the typechecker).

Changelog: [Internal] - JS API snapshot changes are a simplification refactor only

Reviewed By: robhogan

Differential Revision: D105150070

fbshipit-source-id: 43b0ef517164332a5cfaee7a5de5747749ac5e7c
This commit is contained in:
Alex Hunt authored and meta-codesync[bot] committed 2026-05-14 04:16:19 -07:00
1 parent a9be1b12c6
commit 0b9969f7f5
7 files changed
+363 -19

No files matched your search

+7 -18
View File
@@ -4,7 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<82e0f2ccc327245285474ce136692c2d>>
* @generated SignedSource<<f535489438a89534f0a4e37d1dc77b08>>
*
* This file was generated by scripts/js-api/build-types/index.js.
*/
@@ -565,7 +565,7 @@ declare const VirtualizedSectionListComponent_default: <
DefaultVirtualizedSectionT
> = DefaultVirtualizedSectionT,
>(
props: Omit<VirtualizedSectionListProps<ItemT, SectionT>, "ref"> & {
props: VirtualizedSectionListProps<ItemT, SectionT> & {
ref?: React.Ref<{
getListRef(): undefined | VirtualizedList_default
scrollToLocation(params: ScrollToLocationParamsType): void
@@ -4604,19 +4604,8 @@ declare type SectionListData<
| (SectionBase<SectionItemT, SectionT> & SectionT)
| SectionT
declare type SectionListProps<ItemT, SectionT = DefaultSectionT> = Omit<
Omit<
VirtualizedSectionListProps<ItemT, SectionT>,
"getItem" | "getItemCount" | "keyExtractor" | "renderItem"
>,
| "extraData"
| "initialNumToRender"
| "inverted"
| "keyExtractor"
| "onEndReached"
| "removeClippedSubviews"
| "renderItem"
| "sections"
| never
VirtualizedSectionListProps<ItemT, SectionT>,
"getItem" | "getItemCount" | "keyExtractor" | "renderItem"
> &
RequiredSectionListProps<ItemT, SectionT> &
OptionalSectionListProps<ItemT, SectionT>
@@ -5994,7 +5983,7 @@ export {
AlertOptions, // a0cdac0f
AlertType, // 5ab91217
AndroidKeyboardEvent, // e03becc8
Animated, // 5254e138
Animated, // 29ce3240
AppConfig, // ce4209a7
AppRegistry, // 5edf0524
AppState, // 12012be5
@@ -6186,9 +6175,9 @@ export {
ScrollViewPropsIOS, // b34b696c
ScrollViewScrollToOptions, // 3313411e
SectionBase, // b376bddc
SectionList, // c7dfd290
SectionList, // 8ef5401d
SectionListData, // 119baf83
SectionListProps, // 54f880fa
SectionListProps, // d88cd6f6
SectionListRenderItem, // 1fad0435
SectionListRenderItemInfo, // 745e1992
Separators, // 6a45f7e3
@@ -258,4 +258,149 @@ describe('simplifyTypes', () => {
`"type Foo<T> = Omit<Bar, \\"touchHistory\\">;"`,
);
});
test('should remove Omit when no keys exist on interface', async () => {
const code = `
interface Foo {
x: string;
}
type Bar = Omit<Foo, "y" | "z">;
`;
const result = await applyPostTransforms(code);
expect(result).toMatchInlineSnapshot(`
"interface Foo {
x: string;
}
type Bar = Foo;"
`);
});
test('should prune Omit keys that do not exist on interface', async () => {
const code = `
interface Foo {
x: string;
y: number;
}
type Bar = Omit<Foo, "x" | "z">;
`;
const result = await applyPostTransforms(code);
expect(result).toMatchInlineSnapshot(`
"interface Foo {
x: string;
y: number;
}
type Bar = Omit<Foo, \\"x\\">;"
`);
});
test('should resolve Omit through interface extends chain', async () => {
const code = `
type Base = {
a: string;
b: number;
};
interface Child extends Base {
c: boolean;
}
type Result = Omit<Child, "a" | "d">;
`;
const result = await applyPostTransforms(code);
expect(result).toMatchInlineSnapshot(`
"type Base = {
a: string;
b: number;
};
interface Child extends Base {
c: boolean;
}
type Result = Omit<Child, \\"a\\">;"
`);
});
test('should resolve Omit through Readonly in interface extends', async () => {
const code = `
type Base = {
a: string;
};
interface Props extends Readonly<Base> {
b: number;
}
type Result = Omit<Props, "a" | "c">;
`;
const result = await applyPostTransforms(code);
expect(result).toMatchInlineSnapshot(`
"type Base = {
a: string;
};
interface Props extends Readonly<Base> {
b: number;
}
type Result = Omit<Props, \\"a\\">;"
`);
});
test('should resolve Omit through interface extending intersection', async () => {
const code = `
type A = {
x: string;
};
type B = {
y: number;
};
interface Props extends Readonly<A & B> {}
type Result = Omit<Props, "x" | "z">;
`;
const result = await applyPostTransforms(code);
expect(result).toMatchInlineSnapshot(`
"type A = {
x: string;
};
type B = {
y: number;
};
interface Props extends Readonly<A & B> {}
type Result = Omit<Props, \\"x\\">;"
`);
});
test('should not prune Omit when type has an index signature', async () => {
const code = `
type Foo = {
x: string;
[key: string]: unknown;
};
type Bar = Omit<Foo, "y">;
`;
const result = await applyPostTransforms(code);
expect(result).toMatchInlineSnapshot(`
"type Foo = {
x: string;
[key: string]: unknown;
};
type Bar = Omit<Foo, \\"y\\">;"
`);
});
test('should not prune Omit when interface extends unknown type', async () => {
const code = `
interface Props extends UnknownBase {
a: string;
}
type Result = Omit<Props, "a" | "b">;
`;
const result = await applyPostTransforms(code);
expect(result).toMatchInlineSnapshot(`
"interface Props extends UnknownBase {
a: string;
}
type Result = Omit<Props, \\"a\\" | \\"b\\">;"
`);
});
});
@@ -0,0 +1,169 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
* @oncall react_native
*/
import type {NodePath} from '@babel/traverse';
const t = require('@babel/types');
/**
* Collect all property keys reachable from a type by resolving through
* interfaces, type aliases, intersections, and Readonly wrappers.
*
* Returns a Set of all keys when the type is fully resolvable, or null
* when any part cannot be resolved (to avoid incorrect pruning).
*/
function collectTypeKeys(
node: $FlowFixMe,
aliasToPathMap: Map<string, NodePath<t.TSTypeAliasDeclaration>>,
interfaceToPathMap: ?Map<string, NodePath<$FlowFixMe>>,
visited?: Set<string>,
): Set<string> | null {
const seen = visited ?? new Set<string>();
if (t.isTSTypeLiteral(node)) {
return collectMemberKeys(node.members);
}
if (t.isTSIntersectionType(node)) {
const allKeys = new Set<string>();
for (const member of node.types) {
const memberKeys = collectTypeKeys(
member,
aliasToPathMap,
interfaceToPathMap,
seen,
);
if (memberKeys == null) {
return null;
}
for (const key of memberKeys) {
allKeys.add(key);
}
}
return allKeys;
}
if (t.isTSTypeReference(node) && t.isIdentifier(node.typeName)) {
const name = node.typeName.name;
// $FlowFixMe[invalid-compare]
if (name === 'Readonly' && node.typeParameters?.params.length === 1) {
return collectTypeKeys(
node.typeParameters.params[0],
aliasToPathMap,
interfaceToPathMap,
seen,
);
}
// Omit<T, K> — return keys of T (a safe superset, avoids under-counting)
// $FlowFixMe[invalid-compare]
if (name === 'Omit' && node.typeParameters?.params.length === 2) {
return collectTypeKeys(
node.typeParameters.params[0],
aliasToPathMap,
interfaceToPathMap,
seen,
);
}
if (seen.has(name)) {
return null;
}
seen.add(name);
const aliasPath = aliasToPathMap.get(name);
if (aliasPath != null) {
return collectTypeKeys(
aliasPath.node.typeAnnotation,
aliasToPathMap,
interfaceToPathMap,
seen,
);
}
if (interfaceToPathMap != null) {
const ifacePath = interfaceToPathMap.get(name);
if (ifacePath != null) {
return collectInterfaceKeys(
ifacePath,
aliasToPathMap,
interfaceToPathMap,
seen,
);
}
}
return null;
}
return null;
}
function collectInterfaceKeys(
ifacePath: NodePath<$FlowFixMe>,
aliasToPathMap: Map<string, NodePath<t.TSTypeAliasDeclaration>>,
interfaceToPathMap: Map<string, NodePath<$FlowFixMe>>,
visited: Set<string>,
): Set<string> | null {
const keys = collectMemberKeys(ifacePath.node.body.body);
if (keys == null) {
return null;
}
if (ifacePath.node.extends != null) {
for (const extendsClause of ifacePath.node.extends) {
if (!t.isIdentifier(extendsClause.expression)) {
return null;
}
const typeRef = t.tsTypeReference(
t.cloneDeep(extendsClause.expression),
extendsClause.typeParameters != null
? t.cloneDeep(extendsClause.typeParameters)
: undefined,
);
const extendsKeys = collectTypeKeys(
typeRef,
aliasToPathMap,
interfaceToPathMap,
visited,
);
if (extendsKeys == null) {
return null;
}
for (const key of extendsKeys) {
keys.add(key);
}
}
}
return keys;
}
function collectMemberKeys(members: $FlowFixMe): Set<string> | null {
const keys = new Set<string>();
for (const member of members) {
if (t.isTSPropertySignature(member) || t.isTSMethodSignature(member)) {
if (t.isIdentifier(member.key)) {
keys.add(member.key.name);
} else if (t.isStringLiteral(member.key)) {
keys.add(member.key.value);
} else {
return null;
}
} else if (t.isTSIndexSignature(member)) {
return null;
}
}
return keys;
}
module.exports = collectTypeKeys;
@@ -15,16 +15,20 @@ const t = require('@babel/types');
export type GatherTypeAliasesVisitorState = {
+aliasToPathMap: Map<string, NodePath<t.TSTypeAliasDeclaration>>,
+interfaceToPathMap?: Map<string, NodePath<t.TSInterfaceDeclaration>>,
};
/**
* Gather all type aliases in the file into a map
* Gather all type aliases and interface declarations in the file into maps
*/
const gatherTypeAliasesVisitor: Visitor<GatherTypeAliasesVisitorState> = {
TSTypeAliasDeclaration(path, state) {
const alias = path.node.id.name;
state.aliasToPathMap.set(alias, path);
},
TSInterfaceDeclaration(path, state) {
state.interfaceToPathMap?.set(path.node.id.name, path);
},
};
export default gatherTypeAliasesVisitor;
@@ -28,11 +28,16 @@ const mergeObjects: PluginObj<BaseVisitorState> = {
string,
NodePath<t.TSTypeAliasDeclaration>,
>();
state.interfaceToPathMap = new Map<
string,
NodePath<t.TSInterfaceDeclaration>,
>();
state.nodeToAliasMap = new Map<t.Node, string>();
state.parentTypeAliases = new Set<string>();
path.traverse(gatherTypeAliasesVisitor, {
aliasToPathMap: state.aliasToPathMap,
interfaceToPathMap: state.interfaceToPathMap,
});
},
@@ -15,6 +15,7 @@ import type {NodePath} from '@babel/traverse';
import {replaceWithCleanup} from './utils';
const collectTypeKeys = require('./collectTypeKeys');
const t = require('@babel/types');
const debug = require('debug')('build-types:transforms:inlineTypes');
@@ -80,6 +81,36 @@ const builtinTypeResolvers: {
const constBody = tsTypeResolver?.(objectType, state.aliasToPathMap);
if (!constBody || !t.isTSTypeLiteral(constBody)) {
const parentKeys = collectTypeKeys(
objectType,
state.aliasToPathMap,
state.interfaceToPathMap,
);
if (parentKeys != null) {
const overlappingKeys = stringLiteralElements.filter((key: string) =>
parentKeys.has(key),
);
if (overlappingKeys.length === 0) {
replaceWithCleanup(state, path, objectType);
path.skip();
return;
}
if (path.node.typeParameters) {
path.node.typeParameters.params[1] =
overlappingKeys.length === 1
? t.tsLiteralType(t.stringLiteral(overlappingKeys[0]))
: t.tsUnionType(
overlappingKeys.map((key: string) =>
t.tsLiteralType(t.stringLiteral(key)),
),
);
}
return;
}
// Resolving the parameter failed, so we cannot do anything but update
// the second type parameter to the resolved keys.
if (path.node.typeParameters) {
@@ -16,6 +16,7 @@ const t = require('@babel/types');
export type BaseVisitorState = {
aliasToPathMap: Map<string, NodePath<t.TSTypeAliasDeclaration>>,
interfaceToPathMap?: Map<string, NodePath<t.TSInterfaceDeclaration>>,
parentTypeAliases?: Set<string>,
nodeToAliasMap: Map<t.Node, string>,
...