Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(replaceType): handle array syntax #455

Merged
merged 3 commits into from
Dec 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/wise-icons-wash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"types-react-codemod": patch
---

Fix a bug when replacing types in shorthand array type notations.

For example, replacing `ReactText` in `ReactText[]` should now result in `(number | string)[]` instead of `number | string[]`.
32 changes: 32 additions & 0 deletions transforms/__tests__/deprecated-react-child.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,35 @@ test("as type parameter", () => {
createAction<React.ReactElement | number | string>()"
`);
});

test("array type syntax", () => {
expect(
applyTransform(`
import { ReactChild } from 'react';
interface Props {
children?: ReactChild[];
}
`),
).toMatchInlineSnapshot(`
"import { ReactElement } from 'react';
interface Props {
children?: (ReactElement | number | string)[];
}"
`);
});

test("Array generic", () => {
expect(
applyTransform(`
import { ReactChild } from 'react';
interface Props {
children?: Array<ReactChild>;
}
`),
).toMatchInlineSnapshot(`
"import { ReactElement } from 'react';
interface Props {
children?: Array<ReactElement | number | string>;
}"
`);
});
12 changes: 10 additions & 2 deletions transforms/utils/replaceType.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,16 @@ function replaceReactType(
},
);
for (const typeReferences of sourceIdentifierTypeReferences) {
const changedIdentifiers = typeReferences.replaceWith((path) => {
return buildTargetTypeReference(path.value);
const changedIdentifiers = typeReferences.forEach((path) => {
const targetNode = buildTargetTypeReference(path.value);
if (
targetNode.type === "TSUnionType" &&
path.parentPath.value.type === "TSArrayType"
) {
path.replace(j.tsParenthesizedType(targetNode));
eps1lon marked this conversation as resolved.
Show resolved Hide resolved
} else {
path.replace(targetNode);
}
});
if (changedIdentifiers.length > 0) {
hasChanges = true;
Expand Down
Loading