• Stars
    star
    240
  • Rank 167,273 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 2 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Collection of transforms for jscodeshift related to `@types/react`

types-react-codemod

Collection of transforms for jscodeshift related to @types/react.

Getting started

The codemod helps to fix potential TypeScript compile errors when upgrading to @types/react@^18.0.0. However, we recommend to apply this codemod if you're using @types/react@^17.0.30.

$ npx types-react-codemod preset-18 ./src
? Pick transforms to apply (Press <space> to select, <a> to toggle all, <i> to invert selection, and <enter> to proce
ed)
❯◯ context-any
 ◉ deprecated-react-type
 ◉ deprecated-sfc-element
 ◉ deprecated-sfc
 ◉ deprecated-stateless-component
 ◯ implicit-children
 ◯ useCallback-implicit-any
All done.
Results:
0 errors
20 unmodified
0 skipped
3 ok
Time elapsed: 0.229seconds

Usage

$ npx types-react-codemod --help
types-react-codemod <codemod> <paths...>

Positionals:
  codemod [string] [required] [choices: "context-any", "deprecated-react-child",
     "deprecated-react-text", "deprecated-react-type", "deprecated-sfc-element",
                             "deprecated-sfc", "deprecated-stateless-component",
        "deprecated-void-function-component", "experimental-refobject-defaults",
      "implicit-children", "preset-18", "preset-19", "useCallback-implicit-any"]
  paths                                                      [string] [required]

Options:
  --version         Show version number                                [boolean]
  --help            Show help                                          [boolean]
  --dry                                               [boolean] [default: false]
  --ignore-pattern                      [string] [default: "**/node_modules/**"]
  --verbose                                           [boolean] [default: false]

Examples:
  types-react-codemod preset-18 ./          Ignores `node_modules` and `build`
  --ignore-pattern                          folders
  "**/{node_modules,build}/**"

Available transforms

Some transforms change code they shouldn't actually change. Fixing all of these requires a lot of implementation effort. When considering false-positives vs false-negatives, codemods opt for false-positives. The reason being that a false-positive can be reverted easily (assuming you have the changed code in Version Control e.g. git) while a false-negative requires manual input.

  • preset-18
  • deprecated-react-type
  • deprecated-sfc-element
  • deprecated-sfc
  • deprecated-stateless-component
  • context-any
  • implicit-children
  • useCallback-implicit-any
  • preset-19
  • deprecated-react-text

preset-18

This codemod combines all codemods for React 18 types. You can interactively pick the codemods included. By default, the codemods that are definitely required to upgrade to @types/react@^18.0.0 are selected. The other codemods may or may not be required. You should select all and audit the changed files regardless.

context-any

 class Component extends React.Component<Props> {
+  context: any
   render() {
		 return this.context.someContextProperty;
	 }
 }

You should only apply this codemod to files where the type-checker complains about access of unknown in this.context. We'll check for any occurence of context (case-sensitive) in a React.Component body (or React.PureComponent). If we find any occurence of context we'll add context: any declaration to the class body.

false-positive on context usage

We'll add context: any even if you write const { context } = props. This simplifies the implementation tremendously and follows the overall rationale for false-positives: it can be reverted easily and at worst restores the behavior of React 17 typings.

false-negative when inheriting from another component

Class inheritance chains are not handled.

class A extends React.Component {}

class B extends A {
	render() {
		// will error since the transform does not add `context: any` to the declaration of `A` nor `B`.
		// It's up to you to decide whether `A` or `B` should have this declaration
		return this.context.value;
	}
}

We'll also miss usage of context if it's accessed outside of the class body e.g.

function getValue(that) {
	return that.context.value;
}

class A extends React.Component {
	render() {
		return getValue(this);
	}
}

This doesn't really follow the general transform rationale of "over-applying" since at worst we restore React 17 behavior. I just think that most class components do not use this.context (or already have a type declaration) somewhere else.

All deprecated- transforms

-React.ReactType
+React.ElementType
-React.SFC
+React.FC
-React.StatelessComponent
+React.FunctionComponent
-React.SFCElement
+React.FunctionComponentElement

They simply rename identifiers with a specific name. If you have a type with the same name from a different package, then the rename results in a false positive. For example, ink also has a StatelessComponent but you don't need to rename that type since it's not deprecated.

implicit-children

-React.FunctionComponent<Props>
+React.FunctionComponent<React.PropsWithChildren<Props>>
-React.FunctionComponent
+React.FunctionComponent<React.PropsWithChildren<unknown>>

This transform will wrap the props type of React.FunctionComponent (and FC, ComponentType, SFC and StatelessComponent) with React.PropsWithChildren. Note, that the transform assumes React.PropsWithChildren is available. We can't add that import since React.PropsWithChildren can be available via tsconfig.json.

implicit-children false-positive pattern A

We'll apply React.PropsWithChildren everytime. If you have a component that doesn't actually take children, we'll not fix what removal of implicit children should've fixed.

Similarly, if your props already have children declared, PropsWithChildren will be redundant. Redundant PropsWithChildren are only problematic stylistically.

implicit-children false-positive pattern B

MyFunctionComponent<Props> where MyFunctionComponent comes from import { FunctionComponent as MyFunctionComponent } from 'react' will be ignored. In other words, the transform will not wrap Props in React.PropsWithChildren. The transform would need to implement scope tracking for this pattern to get fixed.

useCallback-implicit-any

-React.useCallback((event) => {})
+React.useCallback((event: any) => {})

This transform should only be applied to files where TypeScript errors with "Parameter '*' implicitly has an 'any' type.(7006)" in useCallback.

useCallback-implicit-any false-positive pattern A

If the callback param is inferrable by TypeScript we might apply any without need. In the example below the type of event is inferrable and adding any essentially reduces type coverage. This is why it's recommended to only apply useCallback-implicit-any to files that produce "Parameter '*' implicitly has an 'any' type.(7006)" when type-checking with @types/react@^18.0.0.

type CreateCallback = () => (event: Event) => void;
-const createCallback: CreateCallback = () => useCallback((event) => {}, [])
+const createCallback: CreateCallback = () => useCallback((event: any) => {}, [])

preset-19

This codemod combines all codemods for React 19 types. You can interactively pick the codemods included. By default, the codemods that are definitely required to upgrade to @types/react@^19.0.0 are selected. The other codemods may or may not be required. You should select all and audit the changed files regardless.

deprecated-react-child

 import * as React from "react";
 interface Props {
-  label?: React.ReactChild;
+  label?: React.ReactElement | number | string;
 }

deprecated-react-child false-negative pattern A

Importing ReactChild via aliased named import will result in the transform being skipped.

import { ReactChild as MyReactChild } from "react";
interface Props {
	// not transformed
	label?: MyReactChild;
}

deprecated-react-text

 import * as React from "react";
 interface Props {
-  label?: React.ReactText;
+  label?: number | string;
 }

deprecated-react-text false-negative pattern A

Importing ReactText via aliased named import will result in the transform being skipped.

import { ReactText as MyReactText } from "react";
interface Props {
	// not transformed
	label?: MyReactText;
}

deprecated-void-function-component

WARNING: Only apply to codebases using @types/react@^18.0.0. In earlier versions of @types/react this codemod would change the typings.

 import * as React from "react";
-const Component: React.VFC = () => {}
+const Component: React.FC = () => {}
-const Component: React.VoidFunctionComponent = () => {}
+const Component: React.FunctionComponent = () => {}

experimental-refobject-defaults

WARNING: This is an experimental codemod to intended for codebases using published types. Only use if you're using DefinitelyTyped/DefinitelyTyped#64896.

RefObject no longer makes current nullable by default

 import * as React from "react";
-const myRef: React.RefObject<View>
+const myRef: React.RefObject<View | null>

experimental-refobject-defaults false-negative pattern A

Importing RefObject via aliased named import will result in the transform being skipped.

import { RefObject as MyRefObject } from "react";

// not transformed
const myRef: MyRefObject<View>;

Supported platforms

The following list contains officially supported runtimes. Please file an issue for runtimes that are not included in this list.

  • Node.js 14.x || 16.x || 17.x || 18.x || 19.x

More Repositories

1

dom-accessibility-api

Implements https://w3c.github.io/accname/
JavaScript
70
star
2

screen-reader-testing-library

Utilities to match the speech output of screen readers when replaying user interactions.
JavaScript
43
star
3

actions-label-merge-conflict

GitHub action that adds a label once a PR has merge conflicts
TypeScript
26
star
4

poe-recraft

WIP: item mods overview and crafting simulator for Path of Exile
TypeScript
11
star
5

material-ui-playroom

Using seek-oss/playroom to showcase material design system using Material-UI
JavaScript
10
star
6

poe-db

relational db backend for Path of Exile's Content.ggpk
JavaScript
5
star
7

dependabot-clickable-commands

Replaces dependabot commands with a button that will post that command instead of you having to type it.
JavaScript
5
star
8

eslint-focus

Allows running ESLint with a single rule on a given directory.
JavaScript
4
star
9

mui-scripts-incubator

incubator for material-ui maintainer scripts
JavaScript
4
star
10

solverfox.dev

Code for my personal site
Svelte
4
star
11

create-sapper-app

JavaScript
3
star
12

test262-report-hermes

Test262 report summary for the Hermes version bundled with React Native
TypeScript
3
star
13

eps1lon

Config files for my GitHub profile.
2
star
14

poe-react-item

[WIP] Path of Exile item related react components
TypeScript
2
star
15

material-ui-treeshaking

JavaScript
2
star
16

express-localhost

debugging localhost.local on Monterey 12.4
JavaScript
2
star
17

poe-mods

Emulates interaction of Mods with Items, Atlas etc. in Path of Exile
TypeScript
2
star
18

aria-activedescendant-static-dynamic

Created with CodeSandbox
JavaScript
2
star
19

TreeStats

aggregated passive tree usage statistics
JavaScript
2
star
20

sapper-hydrate-focus

JavaScript
1
star
21

testing-library-react-hooks-impure

Repro for https://github.com/testing-library/react-hooks-testing-library/issues/546
JavaScript
1
star
22

poe-i18n

i18n utility for Path of Exile
TypeScript
1
star
23

persist-size-snapshot

JavaScript
1
star
24

rsc-render-unserializeable

rsc-render-unserializeable
CSS
1
star
25

release-health

Created with CodeSandbox
JavaScript
1
star
26

mui-workflow-maintenance

experimenting with actions for Material-UI maintenance
JavaScript
1
star
27

esquery-cli

Command-line interface for `esquery`
JavaScript
1
star
28

sapper-cypress-events

JavaScript
1
star
29

berry-sapper

sveltejs/sapper-template + yarn v2
JavaScript
1
star
30

react-devtools-hook-inspection-experimental

Fixture to test RDT hook inspection in prod
HTML
1
star
31

poe_mod_repository

Repository of mods in Path Of Exile and their interaction with monsters, items etc
JavaScript
1
star
32

open-sauced-goals

1
star
33

vax-notify

Impfterminvergabe Informationsportal aber mit mehr opt-out anstatt opt-in
JavaScript
1
star
34

tslint-plugin-react-hooks

eslint-plugin-react-hooks for tslint
JavaScript
1
star
35

codemod-missing-await-act

WIP Adds missing await to act calls (or its callers)
JavaScript
1
star