diff --git a/.changeset/wise-icons-wash.md b/.changeset/wise-icons-wash.md new file mode 100644 index 00000000..97be277a --- /dev/null +++ b/.changeset/wise-icons-wash.md @@ -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[]`. diff --git a/transforms/__tests__/deprecated-react-child.js b/transforms/__tests__/deprecated-react-child.js index 355e59a7..604b1cc8 100644 --- a/transforms/__tests__/deprecated-react-child.js +++ b/transforms/__tests__/deprecated-react-child.js @@ -121,3 +121,35 @@ test("as type parameter", () => { createAction()" `); }); + +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; + } + `), + ).toMatchInlineSnapshot(` + "import { ReactElement } from 'react'; + interface Props { + children?: Array; + }" + `); +}); diff --git a/transforms/utils/replaceType.js b/transforms/utils/replaceType.js index 712bcf50..f06e8994 100644 --- a/transforms/utils/replaceType.js +++ b/transforms/utils/replaceType.js @@ -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)); + } else { + path.replace(targetNode); + } }); if (changedIdentifiers.length > 0) { hasChanges = true;