mirror of
https://github.com/facebook/react-native.git
synced 2026-11-18 20:19:07 +00:00
Convert select component types to interface in TS typegen (#56809)
Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/56809 #### Motivation Adds (preserves) compatibility of Nativewind and Expo Web type augmentations with the Strict TypeScript API. - These libraries rely on key React Native component types being defined as `interface`, not `type`, since TS module augmentation only supports `interface` declarations. - Previously, our opt-in generated TypeScript types (Strict TypeScript API) emitted all props types as `type Foo = Readonly<...>` ), matching Flow source. However, this API change vs our manual types (which predominantly used `interface` on props) breaks library compatibility in these cases. - This is very awkward to otherwise solve in user space — so opt for backwards compatibility in our new types. #### Primer TypeScript module augmentation lets a library extend an existing module's types without modifying the source. e.g. In Nativewind ([source](https://www.nativewind.dev/docs/guides/third-party-components)): ```ts declare module 'react-native' { interface ScrollViewProps extends ViewProps, ScrollViewPropsIOS, ScrollViewPropsAndroid, Touchable { contentContainerClassName?: string; indicatorClassName?: string; } interface FlatListProps<ItemT> extends VirtualizedListProps<ItemT> { columnWrapperClassName?: string; } interface ViewProps { className?: string; } } ``` Expo's `react-native-web.d.ts` ([source](https://unpkg.com/expo@54.0.31/types/react-native-web.d.ts)) also follows the same pattern across several component props types. #### Changes Add new `build-types` transform, implementing an opt-in `/** build-types emit-as-interface */` annotation, converting eligible `type` aliases to `interface` declarations. - Changing the Flow source files directly isn't viable — Flow doesn't support `interface extends Omit<>`, and several of these types use `Omit<>` in their composition. The post-transform operates on the TypeScript output where `interface extends Readonly<Omit<...>>` is valid. The following emitted types are updated: | Type | Augmented by | Source | |---|---|---| | `ViewProps` | `className?` | [Nativewind](https://www.nativewind.dev/docs/guides/third-party-components), [Expo](https://unpkg.com/expo@54.0.31/types/react-native-web.d.ts) | | `ScrollViewProps` | `contentContainerClassName?`, `indicatorClassName?` | [Nativewind](https://www.nativewind.dev/docs/guides/third-party-components) | | `ImagePropsBase` | `className?` | [Expo](https://unpkg.com/expo@54.0.31/types/react-native-web.d.ts) | | `SwitchProps` | `className?` | [Expo](https://unpkg.com/expo@54.0.31/types/react-native-web.d.ts) | | `TouchableWithoutFeedbackProps` | `className?` | [Expo](https://unpkg.com/expo@54.0.31/types/react-native-web.d.ts) | | `InputAccessoryViewProps` | `className?` | [Expo](https://unpkg.com/expo@54.0.31/types/react-native-web.d.ts) | `FlatListProps` is not included in this PR: its bare intersection (no `Readonly<>` wrapper) has a conflicting `fadingEdgeLength` property across constituent types that cannot be expressed as a single `extends` clause without hitting TS2320. This will be addressed in a follow-up. `VirtualizedListWithoutRenderItemProps<T>` in `react-native/virtualized-lists` is separately owned and not changed here. Changelog: [General][Changed] - **Strict TypeScript API**: Select component props types are now `interface` declarations, enabling module augmentation by libraries like NativeWind and Expo (preserve compatibility) Reviewed By: robhogan Differential Revision: D104808984 fbshipit-source-id: 69c74fde1180a21c7241be53f010702710672638
This commit is contained in:
1 parent
82536f230f
commit
db89600b56
11 files changed
+527
-155
No files matched your search
+158
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
const convertTypeAliasesToInterfaces = require('../convertTypeAliasesToInterfaces');
|
||||
const babel = require('@babel/core');
|
||||
|
||||
async function transform(code: string): Promise<string> {
|
||||
const result = await babel.transformAsync(code, {
|
||||
plugins: [
|
||||
'@babel/plugin-syntax-typescript',
|
||||
convertTypeAliasesToInterfaces,
|
||||
],
|
||||
});
|
||||
|
||||
return result?.code ?? '';
|
||||
}
|
||||
|
||||
describe('convertTypeAliasesToInterfaces', () => {
|
||||
test('should not convert type without annotation', async () => {
|
||||
const result = await transform(
|
||||
'declare type ViewProps = Readonly<A & B & C>',
|
||||
);
|
||||
expect(result).toBe('declare type ViewProps = Readonly<A & B & C>;');
|
||||
});
|
||||
|
||||
test('should convert Readonly intersection of type references', async () => {
|
||||
const result = await transform(
|
||||
`/** @build-types emit-as-interface */
|
||||
declare type ViewProps = Readonly<A & B & C>`,
|
||||
);
|
||||
expect(result).toMatchInlineSnapshot(
|
||||
`"declare interface ViewProps extends Readonly<A & B & C> {}"`,
|
||||
);
|
||||
});
|
||||
|
||||
test('should convert Readonly intersection with inline object literal', async () => {
|
||||
const result = await transform(
|
||||
`/** @build-types emit-as-interface */
|
||||
declare type Props = Readonly<A & B & { x?: string; y: number }>`,
|
||||
);
|
||||
expect(result).toMatchInlineSnapshot(`
|
||||
"declare interface Props extends Readonly<A & B> {
|
||||
readonly x?: string;
|
||||
readonly y: number;
|
||||
}"
|
||||
`);
|
||||
});
|
||||
|
||||
test('should convert Readonly wrapping pure object literal', async () => {
|
||||
const result = await transform(
|
||||
`/** @build-types emit-as-interface */
|
||||
declare type Props = Readonly<{ a: string; b?: number }>`,
|
||||
);
|
||||
expect(result).toMatchInlineSnapshot(`
|
||||
"declare interface Props {
|
||||
readonly a: string;
|
||||
readonly b?: number;
|
||||
}"
|
||||
`);
|
||||
});
|
||||
|
||||
test('should convert plain object literal without Readonly', async () => {
|
||||
const result = await transform(
|
||||
`/** @build-types emit-as-interface */
|
||||
declare type Props = { readonly a: string; readonly b?: number }`,
|
||||
);
|
||||
expect(result).toMatchInlineSnapshot(`
|
||||
"declare interface Props {
|
||||
readonly a: string;
|
||||
readonly b?: number;
|
||||
}"
|
||||
`);
|
||||
});
|
||||
|
||||
test('should convert intersection without Readonly', async () => {
|
||||
const result = await transform(
|
||||
`/** @build-types emit-as-interface */
|
||||
declare type Props = A & B`,
|
||||
);
|
||||
expect(result).toMatchInlineSnapshot(
|
||||
`"declare interface Props extends Readonly<A & B> {}"`,
|
||||
);
|
||||
});
|
||||
|
||||
test('should preserve generic type parameters', async () => {
|
||||
const result = await transform(
|
||||
`/** @build-types emit-as-interface */
|
||||
declare type FlatListProps<ItemT> = Omit<VLP, "data"> & BaseProps<ItemT>`,
|
||||
);
|
||||
expect(result).toMatchInlineSnapshot(
|
||||
`"declare interface FlatListProps<ItemT> extends Readonly<Omit<VLP, \\"data\\"> & BaseProps<ItemT>> {}"`,
|
||||
);
|
||||
});
|
||||
|
||||
test('should handle Readonly wrapping Omit in intersection', async () => {
|
||||
const result = await transform(
|
||||
`/** @build-types emit-as-interface */
|
||||
declare type Props = Readonly<Omit<ViewProps, "style"> & { alt?: string }>`,
|
||||
);
|
||||
expect(result).toMatchInlineSnapshot(`
|
||||
"declare interface Props extends Readonly<Omit<ViewProps, \\"style\\">> {
|
||||
readonly alt?: string;
|
||||
}"
|
||||
`);
|
||||
});
|
||||
|
||||
test('should preserve surrounding declarations', async () => {
|
||||
const result = await transform(
|
||||
`declare type Foo = string;
|
||||
/** @build-types emit-as-interface */
|
||||
declare type Bar = Readonly<A & B>;
|
||||
declare type Baz = number;`,
|
||||
);
|
||||
expect(result).toMatchInlineSnapshot(`
|
||||
"declare type Foo = string;
|
||||
declare interface Bar extends Readonly<A & B> {}
|
||||
declare type Baz = number;"
|
||||
`);
|
||||
});
|
||||
|
||||
test('should convert exported type with annotation on export', async () => {
|
||||
const result = await transform(
|
||||
`/** @build-types emit-as-interface */
|
||||
export type Props = Readonly<A & B>`,
|
||||
);
|
||||
expect(result).toMatchInlineSnapshot(
|
||||
`"export interface Props extends Readonly<A & B> {}"`,
|
||||
);
|
||||
});
|
||||
|
||||
test('should throw on unsupported type structure', async () => {
|
||||
await expect(
|
||||
transform(
|
||||
`/** @build-types emit-as-interface */
|
||||
declare type Props = string | number`,
|
||||
),
|
||||
).rejects.toThrow(
|
||||
"Unsupported type structure for @build-types emit-as-interface on 'Props'",
|
||||
);
|
||||
});
|
||||
|
||||
test('should handle single type reference', async () => {
|
||||
const result = await transform(
|
||||
`/** @build-types emit-as-interface */
|
||||
declare type Props = Readonly<ViewProps>`,
|
||||
);
|
||||
expect(result).toMatchInlineSnapshot(
|
||||
`"declare interface Props extends Readonly<ViewProps> {}"`,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,193 @@
|
||||
/**
|
||||
* 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 {PluginObj} from '@babel/core';
|
||||
|
||||
import * as t from '@babel/types';
|
||||
|
||||
const ANNOTATION_PATTERN = /@build-types\s+emit-as-interface\b/;
|
||||
|
||||
/**
|
||||
* Convert `type` aliases annotated with `@build-types emit-as-interface` to
|
||||
* an `interface` declaration.
|
||||
*
|
||||
* Nativewind and Expo/react-native-web rely on TypeScript module augmentation
|
||||
* to extend props like `className` on React Native component types. This is
|
||||
* only possible on `interface` declarations (open), not `type` (closed).
|
||||
*/
|
||||
function convertToInterface(path: $FlowFixMe): void {
|
||||
stripAnnotationComments(path);
|
||||
|
||||
const {typeAnnotation} = path.node;
|
||||
let innerType = typeAnnotation;
|
||||
let isReadonly = false;
|
||||
|
||||
if (
|
||||
t.isTSTypeReference(typeAnnotation) &&
|
||||
t.isIdentifier(typeAnnotation.typeName, {name: 'Readonly'}) &&
|
||||
typeAnnotation.typeParameters?.params.length === 1
|
||||
) {
|
||||
isReadonly = true;
|
||||
innerType = typeAnnotation.typeParameters.params[0];
|
||||
}
|
||||
|
||||
const extendsClauses: Array<t.TSExpressionWithTypeArguments> = [];
|
||||
const bodyMembers: Array<t.TSTypeElement> = [];
|
||||
|
||||
if (t.isTSIntersectionType(innerType)) {
|
||||
const refMembers: Array<t.TSType> = [];
|
||||
for (const member of innerType.types) {
|
||||
if (t.isTSTypeLiteral(member)) {
|
||||
const clonedMembers = t.cloneDeep(member).members;
|
||||
if (isReadonly) {
|
||||
makePropertiesReadonly(clonedMembers);
|
||||
}
|
||||
bodyMembers.push(...clonedMembers);
|
||||
} else {
|
||||
refMembers.push(t.cloneDeep(member));
|
||||
}
|
||||
}
|
||||
if (refMembers.length > 0) {
|
||||
const refsType =
|
||||
refMembers.length === 1
|
||||
? refMembers[0]
|
||||
: t.tsIntersectionType(refMembers);
|
||||
if (isReadonly) {
|
||||
extendsClauses.push(
|
||||
t.tsExpressionWithTypeArguments(
|
||||
t.identifier('Readonly'),
|
||||
t.tsTypeParameterInstantiation([refsType]),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
extendsClauses.push(typeToExtendsClause(refsType, false));
|
||||
}
|
||||
}
|
||||
} else if (t.isTSTypeLiteral(innerType)) {
|
||||
const clonedMembers = t.cloneDeep(innerType).members;
|
||||
if (isReadonly) {
|
||||
makePropertiesReadonly(clonedMembers);
|
||||
}
|
||||
bodyMembers.push(...clonedMembers);
|
||||
} else if (t.isTSTypeReference(innerType)) {
|
||||
extendsClauses.push(typeToExtendsClause(innerType, isReadonly));
|
||||
} else {
|
||||
throw new Error(
|
||||
`Unsupported type structure for @build-types emit-as-interface on '${path.node.id.name}'. Only object literals, type references, and intersections of these are supported.`,
|
||||
);
|
||||
}
|
||||
|
||||
const interfaceNode = t.tsInterfaceDeclaration(
|
||||
t.cloneDeep(path.node.id),
|
||||
path.node.typeParameters
|
||||
? t.cloneDeep(path.node.typeParameters)
|
||||
: undefined,
|
||||
extendsClauses.length > 0 ? extendsClauses : undefined,
|
||||
t.tsInterfaceBody(bodyMembers),
|
||||
);
|
||||
interfaceNode.declare = path.node.declare ?? false;
|
||||
|
||||
path.replaceWith(interfaceNode);
|
||||
}
|
||||
|
||||
function hasAnnotationInComments(
|
||||
comments: ?ReadonlyArray<{type: string, value: string}>,
|
||||
): boolean {
|
||||
return (
|
||||
Array.isArray(comments) &&
|
||||
comments.some(
|
||||
comment =>
|
||||
comment.type === 'CommentBlock' &&
|
||||
ANNOTATION_PATTERN.test(comment.value),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function hasEmitAsInterfaceAnnotation(path: $FlowFixMe): boolean {
|
||||
if (hasAnnotationInComments(path.node.leadingComments)) {
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
path.parentPath?.isExportNamedDeclaration() &&
|
||||
hasAnnotationInComments(path.parentPath.node.leadingComments)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function typeToExtendsClause(
|
||||
tsType: t.TSType,
|
||||
wrapInReadonly: boolean,
|
||||
): t.TSExpressionWithTypeArguments {
|
||||
if (wrapInReadonly) {
|
||||
return t.tsExpressionWithTypeArguments(
|
||||
t.identifier('Readonly'),
|
||||
t.tsTypeParameterInstantiation([t.cloneDeep(tsType)]),
|
||||
);
|
||||
}
|
||||
|
||||
if (t.isTSTypeReference(tsType) && t.isIdentifier(tsType.typeName)) {
|
||||
return t.tsExpressionWithTypeArguments(
|
||||
t.cloneDeep(tsType.typeName),
|
||||
tsType.typeParameters ? t.cloneDeep(tsType.typeParameters) : undefined,
|
||||
);
|
||||
}
|
||||
|
||||
return t.tsExpressionWithTypeArguments(
|
||||
t.identifier('Readonly'),
|
||||
t.tsTypeParameterInstantiation([t.cloneDeep(tsType)]),
|
||||
);
|
||||
}
|
||||
|
||||
function makePropertiesReadonly(members: Array<t.TSTypeElement>): void {
|
||||
for (const member of members) {
|
||||
if (t.isTSPropertySignature(member)) {
|
||||
member.readonly = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function stripAnnotationComments(path: $FlowFixMe): void {
|
||||
const filter = (comments: $FlowFixMe) =>
|
||||
comments?.filter(
|
||||
(c: $FlowFixMe) =>
|
||||
!(c.type === 'CommentBlock' && ANNOTATION_PATTERN.test(c.value)),
|
||||
) ?? [];
|
||||
path.node.leadingComments = filter(path.node.leadingComments);
|
||||
if (path.parentPath?.isExportNamedDeclaration()) {
|
||||
path.parentPath.node.leadingComments = filter(
|
||||
path.parentPath.node.leadingComments,
|
||||
);
|
||||
}
|
||||
const target = path.parentPath?.isExportNamedDeclaration()
|
||||
? path.parentPath
|
||||
: path;
|
||||
const prevSibling = target.getPrevSibling();
|
||||
if (prevSibling?.node) {
|
||||
prevSibling.node.trailingComments = filter(
|
||||
prevSibling.node.trailingComments,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const visitor: PluginObj<unknown> = {
|
||||
visitor: {
|
||||
TSTypeAliasDeclaration(path) {
|
||||
if (!hasEmitAsInterfaceAnnotation(path)) {
|
||||
return;
|
||||
}
|
||||
convertToInterface(path);
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = visitor;
|
||||
@@ -29,6 +29,7 @@ const preTransforms: Array<PreTransformFn> = [
|
||||
require('./transforms/flow/ensureNoUnprefixedProps'),
|
||||
];
|
||||
const postTransforms = (filePath: string): Array<PluginObj<unknown>> => [
|
||||
require('./transforms/typescript/convertTypeAliasesToInterfaces'),
|
||||
require('./transforms/typescript/replaceDefaultExportName')(filePath),
|
||||
];
|
||||
const prettierOptions = {parser: 'babel'};
|
||||
|
||||
Reference in new issue
Block a user