Convert react app to typescript

Convert react app to typescript DEFAULT

Migrating a React Codebase to TypeScript

Note: This post was originally published in July and has been updated for accuracy and comprehensiveness (you know, hooks and stuff).

More and more React developers are starting to appreciate the type safety TypeScript allows when working with React. Libraries like Formik, react-apollo or anything from the Prisma people have been leveraging it for years.

Here are the steps to you need to take to get that warm fuzzy feeling when your code compiles.

Migrate create-react-app

create-react-app comes with TypeScript support as of version Converting is quite straight-forward now:

Install Dependencies

1$ yarn add typescript @types/node @types/react @types/react-dom @types/jest

Add a TypeScript Config

Add a file at your project root level with the following content:

1{

2"compilerOptions":{

3"target":"es5",

4"lib":[

5"dom",

6"dom.iterable",

7"esnext"

8],

9"allowJs":true,

10"skipLibCheck":true,

11"esModuleInterop":true,

12"allowSyntheticDefaultImports":true,

13"strict":true,

14"forceConsistentCasingInFileNames":true,

15"module":"esnext",

16"moduleResolution":"node",

17"resolveJsonModule":true,

18"isolatedModules":true,

19"noEmit":true,

20"jsx":"react"

21},

22"include":[

23"src"

24]

25}

Change the file endings

Change all file endings from to . It’s a must for your but you can do it for all your JavaScript files right now if you want.

Feel free to set to in your tsconfig.json for now and sprinkle type annotations over your codebase where TypeScript complains. No need to fix everything in one go. Adding types can be done in small, self-contained pull-requests later on.

Import types for your libraries

The people over at DefinitelyTyped have ready-made types for almost all the libraries out there, so take advantage of it. Add them via yarn or npm (Example: get via ).

Troubleshooting

You will run into some problems on your way to the perfect TypeScript codebase but you will also learn a lot in the process. Here are some of the issues that came up for me:

Importing images

Note: This works out of the box now.

1declare module "*.png"{

2const value: string;

3exportdefault value;

4}

TypeScript is not happy if you slap on unrecognized props to your custom component. To illustrate what I mean with this check out this code fragment:

1constHeader= styled.div`

2 color: BlanchedAlmond;

3`

4

5

6<Header

7 isDragging={snapshot.isDragging}

8/>

9

Here I’m using for drag-and-drop and the Header-div needs an additional prop. TypeScript doesn’t like it (for good reason: a having a attribute is unexpected).

The solution: My preferred CSS-in-JS library (emotion) allows the following:

1interfaceMyHeaderProps{

2 isDragging: any;

3}

4

5constHeader=

6styled("div")<

7MyHeaderProps>

8`

9 padding: 0px 0 0 8px;

10 margin: 5px;

11 display: flex;

12 justify-content: space-between;

13`;

See the emotion docs on TypeScript.

Use VS Code

Besides being an excellent mix of an editor and IDE, VisualStudio Code is closely developed with TypeScript (both are from Microsoft). Definitely check it out if you haven’t!

Typing Your Codebase

Functional Components

I type my components with even though it has some downsides.

1typeMyBananaProps={}

2

3constMyComponent:React.FC<MyBananaProps>=props=>{}

Note that you don’t need to type the argument again in your arrow function.

The alternative is to just type your props:

1typeMyBananaProps={}

2

3constMyComponent=(props: MyBananaProps)=>{}

There’s actually quite the mess with regard to typing React components. There’s , , , , etc… But unless you run into problems keep it simple.

Give me something to type any generic render output

React.ReactNode. It’s not very type-safe but it gets the job done when you want to allow basically everything. The internal typings look like this:

1typeReactNode=ReactChild|ReactFragment|ReactPortal|boolean|null| undefined;

2

3

4typeReactChild=ReactElement|ReactText;

5

6

7typeReactText=string|number;

Typing Events

Events can be tricky to type correctly but it’s worth it to catch potential bugs. In general, you want to import the most specific event from React and use its generics to tell TS on what HTML element this event will be triggered:

1importReact,{MouseEvent,KeyboardEvent}from"react";

2

3constMyComponent=()=>{

4consthandleClick=(event: MouseEvent<HTMLButtonElement>)=>{};

5

6consthandleKeyDown=(event: KeyboardEvent<HTMLInputElement>)=>{};

7

8return(

9<>

10<button onClick={handleClick}>Click me</button>

11<input onKeyDown={handleKeyDown}/>

12</>

13);

14};

Here is a quick overview of event types I found:

1BaseSyntheticEvent

2SyntheticEvent

3ClipboardEvent

4CompositionEvent

5DragEvent

6PointerEvent

7FocusEvent

8FormEvent

9InvalidEvent

10ChangeEvent

11KeyboardEvent

12MouseEvent

13TouchEvent

14UIEvent

15WheelEvent

16AnimationEvent

17TransitionEvent

Typing Hooks

Most built-in hooks (useReducer, useContext, useEffect, useCallback, useMemo) should be straight-forward to type so I will focus on useState and useRef.

useState

Simple types get inferred:

1

2const[counter, setCounter]= useState<number>(0);

3

4

5const[counter, setCounter]=useState(0);

For more complex types it’s quite straight-forward:

1typeMyCustomState={counter:number, running:false}

2

3const[myCustomState, setMyCustomState]= useState<MyCustomState>(yourInitialState)

4

5

6

7const[myCustomState, setMyCustomState]= useState<MyCustomState|undefined>(undefined)

useRef

This hook can be troublesome as many developers like to take a big step around DOM typings. But it’s actually not so bad:

1constMyComponent=()=>{

2const myButtonRef = useRef<HTMLButtonElement>(null)

3const myDivRef = useRef<HTMLDivElement>(null)

4const myCircleRef = useRef<SVGCircleElement>(nul);

5

6if(myButtonRef.current){

7 myButtonRef.current.focus();

8}

9

10return(

11<>

12<button ref={myButtonRef}/>

13<div ref={myDivRef}/>

14<svg>

15<circle ref={myCircleRef}

16</svg>

17</>

18)

19}

You don’t need to add to the generic type (e.g. ) as the React typings have overloads for this:

1

2function useRef<T>(initialValue:T|null):RefObject<T>;

But you still need the check of the property of your ref (see line 6 above), as gets initialized with before it grabs its ref.

Where to learn more

Sours: https://markpollmann.com/react-moving-to-typescript/

How to Migrate a React App to TypeScript from JavaScript

When I first started learning TypeScript, one of the suggestions I often heard was, “convert one of your existing projects! It’s the best way to learn!”

The purpose of this article is to be that friend for you and help you migrate your own project to TypeScript. For context, I will be using pieces from a personal project which I migrated while going through this process myself.

The Plan

To make this process feel less daunting, we’ll break this down into steps so that you can execute the migration in individual chunks. I always find this helpful when taking on a large task. Here are all the steps we’ll take to migrate our project:

  1. Add TypeScript
  2. Add
  3. Start simple
  4. Convert all files
  5. Increase strictness
  6. Clean it up
  7. Celebrate

NOTE: the most important step in this whole process is number 7. Although we can only get there by working through them in sequential order.

1. Add TypeScript to the Project

First, we need to add TypeScript to our project. Assuming your React project was bootstrapped with , we can follow the docs and run:

or if you’re using :

Notice we haven’t changed anything to TypeScript yet. If we run the command to start the project locally ( in my case), nothing should be different. If that’s the case, then great! We’re ready for the next step.

2. Add the

Before we can take advantage of TypeScript, we need to configure this via the . The simplest way for us to get started is to scaffold one using this command:

This gets us some basics.

We have not yet interacted with TypeScript. We have only taken the necessary actions to get things ready. Our next step is to migrate a file to TypeScript. With this, we can complete this step and move onto the next.

3. Start with a Simple Component

The beauty of TypeScript is that you can incrementally adopt it. We can start with a simple component for our first piece of this migration. For my project, I’m going to start with an SVG component that looks like this:

To properly convert this, we need to do two things:

  1. Change the file extension to
  2. Add the type annotation

Since this component takes no props, the only thing we need to change is this:

Let’s double-check that things are still working by running the project to ensure we didn’t break anything. Notice, here will automatically detect the new changes and modify our for us! Voila! How beautiful is that?

And if all is well, our project will remain in working condition. Give yourself a pat on the back! You’ve successfully migrated your first file to TypeScript. If we wanted to stop here, we could, but let’s push forward.

4. Convert All Files

The next step is to do what we did for step 3, but for all files in the project. If the project you’re migrating is rather large, I suggest doing this over multiple iterations. Otherwise, you may tire yourself out.

During this step, you may need to add additional packages depending on what third-party libraries you’re using. For instance, I am using so I had to run to add the types as a .

Here are some other things to keep in mind as you do this:

  • Suppress TypeScript errors by adding on the line before the error
  • If a file uses jsx (i.e. ), the file extension must be instead of
  • Run the project locally to make sure things are still working (they should be)

After you’ve completed this step, the hard stuff is done! Our project will be in TypeScript, but we’ll need to increase the strictness to take advantage of the benefits.

5. Increase Strictness

Now we are ready to increase the strictness by enabling stricter rules in our . Thankfully, will inform us of any type errors while running our project locally. We will follow the process like so:

  1. enable rule
  2. start project locally
  3. fix errors

And we will repeat this process for the following rules:

    I want to share a tip. If you find that something implicitly has the type and you’re not sure how to fix it in that moment, don’t. Create this and use it to hush the error:

    Our goal is to move forward quickly and go back later to fix these.

    This will bring a greater amount of type safety to our project. If you’d like to read more about compiler options, you can read about it in the TypeScript Handbook.

    Once we’ve done this, we can then replace these:

      with this:

      which also enables these strict options:

      • strictBindCallApply
      • strictNullChecks
      • strictFunctionTypes
      • strictPropertyInitialization

      At this point, we have reached a standard level of strictness in our project. If we want to add additional checks, we can add these rules:

        Once we’ve reached a level of strictness that we’re happy with, we can proceed to the next step.

        6. Clean Up Shortcuts

        If you added or took advantage of a type, now is the time to go back and fix them. We don’t have to do these all at once, or ever, but this would be the last step to ensure maximum type safety across your project.

        Sometimes the effort to fix these is not worth the time, and other times it is. You’ll have to discuss with your team and decide what makes sense.

        7. Celebrate

        We did it! We officially migrated our project to TypeScript. Take a moment to celebrate your work. It was certainly not a trivial task. Especially if you were working in a large codebase.

        Things to Remember

        As we reflect on our efforts, here are some things to remember when migrating a project from React to TypeScript.

        Start Small

        Take advantage of TypeScript’s ability to gradually adopt it. Go one file at a time at your own pace. Do what makes sense for you and your team. Do not try to tackle it all at once.

        Increase Strictness Over Time

        There is no need to start with maximum strictness from the beginning. It is a journey. Increase the level as you have time. Eventually, you will reach a level that feels comfortable. Do not feel bad if you do not have % strictness. Some type safety is better than no type safety.

        Lean on Shortcuts

        The and the tip for are there to help lessen the burden of the migration. Not everything needs to changed at once. Use the shortcuts as you need but do not feel bad for using them. Again, the point is to migrate, but it should not be painful. Over time, you can prioritize replacing these things with proper type safety. But remember, these tools are at your disposal so use them.

        This is not the only approach for migrating React projects to TypeScript. However, it is what works for me. I hope it helps you as much as it helped me.

        Originally published by Joe Previte at https://www.sitepoint.com

        #reactjs #tyepscript #javascript #webdev

        What is GEEK

        Buddha Community

        How to Migrate a React App to TypeScript from JavaScript
        Sours: https://morioh.com/p/dcac0bb6de2e
        1. Section 8 housing morgantown wv
        2. Ford focus 2006 seat covers
        3. What happened to fit stock

        TypeScript React Conversion Guide

        This walkthrough illustrates how to adopt TypeScript in an existing React/Babel/Webpack project. We'll start with a TicTacToe project written fully in JavaScript in the folder as an example. By the end, you will have a TicTacToe project fully written with TypeScript.

        If you are starting a new React project instead of converting one, you can use this tutorial.

        Adopting TypeScript in any project can be broken down into 2 phases:

        • Adding the TypeScript compiler (tsc) to your build pipeline.
        • Converting JavaScript files into TypeScript files.

        Understand the existing JavaScript project

        Before we dive into TypeScript adoption, let's take a look at the structure of the TicTacToe app -- it contains a few components and looks like the below (with or without TypeScript).

        As shown in , the app already includes React/ReactDOM, Webpack as the bundler & task runner, and the babel-loader Webpack plugin to use Babel for ES6 and JSX transpilation. The project initially has the below overall layout before we adopt TypeScript:

        Add TypeScript compiler to build pipeline

        Install dependencies

        To get started, open a terminal and to the folder. Install all dependencies defined in .

        cd TicTacToe_JS npm install

        Additionally, install TypeScript (3 or higher), ts-loader and source-map-loader as dev dependencies if you haven't. ts-loader is a Webpack plugin that helps you compile TypeScript code to JavaScript, much like babel-loader for Babel. There are also other alternative loaders for TypeScript! Source-map-loader adds source map support for debugging.

        npm install --save-dev typescript ts-loader source-map-loader

        Get the type declaration files (.d.ts files) from @types for any library in use. For this project, we have React and ReactDOM.

        npm install --save @types/react @types/react-dom

        If you are using an older version of React or ReacDOM that is incompatible with the latest .d.ts files from @types, you can specify a version number for or in .

        Configure TypeScript

        Next, configure TypeScript by creating a file in the folder, and add:

        {"compilerOptions": {"outDir": "./dist/",// path to output directory"sourceMap": true,// allow sourcemap support"strictNullChecks": true,// enable strict null checks as a best practice"module": "es6",// specify module code generation"jsx": "react",// use typescript to transpile jsx to js"target": "es5",// specify ECMAScript target version"allowJs": true// allow a partial TypeScript and JavaScript codebase},"include": ["./src/"]}

        You can edit some of the options or add more based on your project's requirements. See more options in the full list of compiler options.

        Set up build pipeline

        To add TypeScript compilation as part of our build process, you need to modify the Webpack config file . This section is specific to Webpack. However, if you are using a different task runner (e.g. Gulp) for your React/Babel project, the idea is the same - replace the Babel build step with TypeScript, as TypeScript also offers transpiling to lower ECMAScript versions and JSX transpilation with a shorter build time in most cases. If you wish, you can also keep Babel by adding a TypeScript build step before Babel and feeding its output to Babel.

        Generally, we need to change in a few ways:

        1. Expand the module resolution extensions to include and files.
        2. Replace with .
        3. Add source-map support.

        Let's modify with the below:

        module.exports={// change to .tsx if necessaryentry: './src/app.jsx',output: {filename: './bundle.js'},resolve: {// changed from extensions: [".js", ".jsx"]extensions: [".ts",".tsx",".js",".jsx"]},module: {rules: [// changed from { test: /\.jsx?$/, use: { loader: 'babel-loader' }, exclude: /node_modules/ },{test: /\.(t|j)sx?$/,use: {loader: 'ts-loader'},exclude: /node_modules/},// addition - add source-map support{enforce: "pre",test: /\.js$/,exclude: /node_modules/,loader: "source-map-loader"}]},externals: {"react": "React","react-dom": "ReactDOM",},// addition - add source-map supportdevtool: "source-map"}

        You can delete and all Babel dependencies from if you no longer need them.

        Note that if you plan to adopt TypeScript in the entry file, you should change to as well. For the time being, we will keep it as .

        You now have the build pipeline correctly set up with TypeScript handling the transpilation. Try bundling the app with the following command and then open in a browser:

        We are assuming you are using addition for to execute npm packages directly

        Transition from JS(X) to TS(X)

        In this part, we will walk through the following steps progressively,

        1. The minimum steps of converting one module to TypeScript.
        2. Adding types in one module to get richer type checking.
        3. Fully adopting TypeScript in the entire codebase.

        While you get the most out of TypeScript by fully adopting it across your codebase, understanding each of the three steps comes in handy as you decide what to do in case you have certain part of your JavaScript codebase you want to leave as-is (think legacy code that no one understands).

        Minimum transition steps

        Let's look at as an example.

        Step one is to rename to . If you are using any editor with TypeScript support such as Visual Studio Code, you should be able to see a few complaints from your editor.

        On line 1 , change the import statement to . This is because while importing a CommonJS module, Babel assumes as default export, while TypeScript does not.

        On line 3 , change the class declaration to . The type declaration of uses generic types and requires providing the types for the property and state object for the component. The use of allows us to pass in any value as the property or state object, which is not useful in terms of type checking but suffices as minimum effort to appease the compiler.

        By now, ts-loader should be able to successfully compile this TypeScript component to JavaScript. Again, try bundling the app with the following command and then open in a browser,

        Add types

        The more type information provided to TypeScript, the more powerful its type checking is. As a best practice, we recommend providing types for all declarations. We will again use the component as an example.

        For any , we should properly define the types of the property and state object. The component has no properties, therefore we can use as type.

        The state object contains only one property which shows the game status (either nothing, someone wins, or draw). Given can only have certain known string literal values, let's use string literal type and define the interface as follow before the class declaration.

        interfaceGameStateBarState{gameState: ""|"X Wins!"|"O Wins!"|"Draw";}

        With the defined interface, change the class declaration,

        exportclassGameStateBarextendsReact.Component<{},GameStateBarState>{}

        Now, supply type information for its members. Note that providing types to all declarations is not required, but recommended for better type coverage.

        // add types for paramsconstructor(props: {}){}handleGameStateChange(e: CustomEvent){}handleRestart(e: Event){}// add types in arrow functionscomponentDidMount(){window.addEventListener("gameStateChange",(e: CustomEvent)=>this.handleGameStateChange(e));window.addEventListener("restart",(e: CustomEvent)=>this.handleRestart(e));}// add types in arrow functionscomponentWillUnmount(){window.removeEventListener("gameStateChange",(e: CustomEvent)=>this.handleGameStateChange(e));window.removeEventListener("restart",(e: CustomEvent)=>this.handleRestart(e));}

        To use stricter type checking, you can also specify useful compiler options in . For example, is a recommended option that triggers the compiler to error on expressions and declarations with an implied type.

        You can also add private/protected modifier to class members for access control. Let's mark and as as they are internal to .

        privatehandleGameStateChange(e: CustomEvent){}privatehandleRestart(e: Event){}

        Again, try bundling the app with the following command and then open in a browser,

        Adopt TypeScript in the entire codebase

        Adopting TypeScript in the entire codebase is more or less repeating the previous two steps for all js(x) files. You may need to make changes additional to what is mentioned above while converting perfectly valid JavaScript to TypeScript. However the TypeScript compiler and your editor (if it has TypeScript support) should give you useful tips and error messages. For instance, parameters can be optional in JavaScript, but in TypeScript all optional parameter must be marked with

        You can see the fully converted TicTacToe project in the folder. Build the app with,

        Run the app by opening .

        Sours: https://github.com/microsoft/TypeScript-React-Conversion-Guide
        Create a React App with TypeScript

        Migrate React App To TypeScript

        For react projects created with create-react-app, it is very easy to migrate to Typescript. This will guarantee type checking and proper linting of the codebase.

        Steps

        1. Install necessary dependencies

        Note: most react/npm packages will require an dependency to work with typescript. So add them accordingly

        2. Change file extensions

        • Change component files from or to
        • Change other javascript files from to
        • Fix import statements
        • Fix any other issues that may arise

        Since react works with es6 syntax, switching to typescript should raise minimal to no issues

        3. Start project

        Starting the project will automatically create a file with all the necessary settings

        4. Add Type to variables and functions

        Append the type for each variable, parameter and return type for each function or method.

        For example, change the following javascript function:

        to the following typescript function:

        Both parameters in the function have a type of and the function also has a return type of

        5. Define Classes/Interfaces for Complex Data

        This includes data from API's and redux state

        Thanks 👍 for making it to the end 👨‍💻 and I really hope you found the content useful.

        Leave a comment below or tweet me @ElishaChibueze if you have any questions or suggestions

        Sours: https://dev.to/elishaking/migrate-react-app-to-typescriptn5

        To typescript convert react app

        TypeScript doesn’t exist in a vacuum. It was built with the JavaScript ecosystem in mind, and a lot of JavaScript exists today. Converting a JavaScript codebase over to TypeScript is, while somewhat tedious, usually not challenging. In this tutorial, we’re going to look at how you might start out. We assume you’ve read enough of the handbook to write new TypeScript code.

        If you’re looking to convert a React project, we recommend looking at the React Conversion Guide first.

        Setting up your Directories

        If you’re writing in plain JavaScript, it’s likely that you’re running your JavaScript directly, where your files are in a , , or directory, and then ran as desired.

        If that’s the case, the files that you’ve written are going to be used as inputs to TypeScript, and you’ll run the outputs it produces. During our JS to TS migration, we’ll need to separate our input files to prevent TypeScript from overwriting them. If your output files need to reside in a specific directory, then that will be your output directory.

        You might also be running some intermediate steps on your JavaScript, such as bundling or using another transpiler like Babel. In this case, you might already have a folder structure like this set up.

        From this point on, we’re going to assume that your directory is set up something like this:

        If you have a folder outside of your directory, you might have one in , and one in as well.

        Writing a Configuration File

        TypeScript uses a file called for managing your project’s options, such as which files you want to include, and what sorts of checking you want to perform. Let’s create a bare-bones one for our project:

        json

        Here we’re specifying a few things to TypeScript:

        1. Read in any files it understands in the directory (with ).
        2. Accept JavaScript files as inputs (with ).
        3. Emit all of the output files in (with ).
        4. Translate newer JavaScript constructs down to an older version like ECMAScript 5 (using ).

        At this point, if you try running at the root of your project, you should see output files in the directory. The layout of files in should look identical to the layout of . You should now have TypeScript working with your project.

        Early Benefits

        Even at this point you can get some great benefits from TypeScript understanding your project. If you open up an editor like VS Code or Visual Studio, you’ll see that you can often get some tooling support like completion. You can also catch certain bugs with options like:

        TypeScript will also warn about unreachable code and labels, which you can disable with and respectively.

        Integrating with Build Tools

        You might have some more build steps in your pipeline. Perhaps you concatenate something to each of your files. Each build tool is different, but we’ll do our best to cover the gist of things.

        Gulp

        If you’re using Gulp in some fashion, we have a tutorial on using Gulp with TypeScript, and integrating with common build tools like Browserify, Babelify, and Uglify. You can read more there.

        Webpack

        Webpack integration is pretty simple. You can use , a TypeScript loader, combined with for easier debugging. Simply run

        shell

        and merge in options from the following into your file:

        js

        It’s important to note that ts-loader will need to run before any other loader that deals with files.

        The same goes for awesome-typescript-loader, another TypeScript loader for Webpack. You can read more about the differences between the two here.

        You can see an example of using Webpack in our tutorial on React and Webpack.

        Moving to TypeScript Files

        At this point, you’re probably ready to start using TypeScript files. The first step is to rename one of your files to . If your file uses JSX, you’ll need to rename it to .

        Finished with that step? Great! You’ve successfully migrated a file from JavaScript to TypeScript!

        Of course, that might not feel right. If you open that file in an editor with TypeScript support (or if you run ), you might see red squiggles on certain lines. You should think of these the same way you’d think of red squiggles in an editor like Microsoft Word. TypeScript will still translate your code, just like Word will still let you print your documents.

        If that sounds too lax for you, you can tighten that behavior up. If, for instance, you don’t want TypeScript to compile to JavaScript in the face of errors, you can use the option. In that sense, TypeScript has a dial on its strictness, and you can turn that knob up as high as you want.

        If you plan on using the stricter settings that are available, it’s best to turn them on now (see Getting Stricter Checks below). For instance, if you never want TypeScript to silently infer for a type without you explicitly saying so, you can use before you start modifying your files. While it might feel somewhat overwhelming, the long-term gains become apparent much more quickly.

        Weeding out Errors

        Like we mentioned, it’s not unexpected to get error messages after conversion. The important thing is to actually go one by one through these and decide how to deal with the errors. Often these will be legitimate bugs, but sometimes you’ll have to explain what you’re trying to do a little better to TypeScript.

        Importing from Modules

        You might start out getting a bunch of errors like , and . In these cases, it’s likely that you’re using modules. While you can just convince TypeScript that these exist by writing out

        ts

        or

        ts

        it’s better to get rid of those calls and use TypeScript syntax for imports.

        First, you’ll need to enable some module system by setting TypeScript’s option. Valid options are , , , and .

        If you had the following Node/CommonJS code:

        js

        or the following RequireJS/AMD code:

        js

        then you would write the following TypeScript code:

        ts

        Getting Declaration Files

        If you started converting over to TypeScript imports, you’ll probably run into errors like . The issue here is that you likely don’t have declaration files to describe your library. Luckily this is pretty easy. If TypeScript complains about a package like , you can just write

        shell

        If you’re using a module option other than , you’ll need to set your option to .

        After that, you’ll be able to import lodash with no issues, and get accurate completions.

        Exporting from Modules

        Typically, exporting from a module involves adding properties to a value like or . TypeScript allows you to use top-level export statements. For instance, if you exported a function like so:

        js

        you could write that out as the following:

        ts

        Sometimes you’ll entirely overwrite the exports object. This is a common pattern people use to make their modules immediately callable like in this snippet:

        js

        You might have previously written that like so:

        js

        In TypeScript, you can model this with the construct.

        ts

        Too many/too few arguments

        You’ll sometimes find yourself calling a function with too many/few arguments. Typically, this is a bug, but in some cases, you might have declared a function that uses the object instead of writing out any parameters:

        js

        In this case, we need to use TypeScript to tell any of our callers about the ways can be called using function overloads.

        ts

        We added two overload signatures to . The first checks states that takes a function (which takes a ), and then a list of s. The second one says that it will take a function as well, and then uses a rest parameter () to state that any number of arguments after that need to be s.

        Sequentially Added Properties

        Some people find it more aesthetically pleasing to create an object and add properties immediately after like so:

        js

        TypeScript will say that you can’t assign to and because it first figured out the type of as which doesn’t have any properties. If you instead moved the declarations into the object literal themselves, you’d get no errors:

        ts

        You could also define the type of and add a type assertion on the object literal.

        ts

        Alternatively, you can just say has the type which is the easiest thing to do, but which will benefit you the least.

        , , and

        You might be tempted to use or to say that a value can have any property on it because is, for most purposes, the most general type. However is actually the type you want to use in those situations, since it’s the most flexible type.

        For instance, if you have something that’s typed as you won’t be able to call methods like on it. Being more general usually means you can do less with a type, but is special in that it is the most general type while still allowing you to do anything with it. That means you can call it, construct it, access properties on it, etc. Keep in mind though, whenever you use , you lose out on most of the error checking and editor support that TypeScript gives you.

        If a decision ever comes down to and , you should prefer . While they are mostly the same, technically is a more general type than in certain esoteric cases.

        Getting Stricter Checks

        TypeScript comes with certain checks to give you more safety and analysis of your program. Once you’ve converted your codebase to TypeScript, you can start enabling these checks for greater safety.

        No Implicit

        There are certain cases where TypeScript can’t figure out what certain types should be. To be as lenient as possible, it will decide to use the type in its place. While this is great for migration, using means that you’re not getting any type safety, and you won’t get the same tooling support you’d get elsewhere. You can tell TypeScript to flag these locations down and give an error with the option.

        Strict & Checks

        By default, TypeScript assumes that and are in the domain of every type. That means anything declared with the type could be or . Since and are such a frequent source of bugs in JavaScript and TypeScript, TypeScript has the option to spare you the stress of worrying about these issues.

        When is enabled, and get their own types called and respectively. Whenever anything is possibly, you can use a union type with the original type. So for instance, if something could be a or , you’d write the type out as .

        If you ever have a value that TypeScript thinks is possibly /, but you know better, you can use the postfix operator to tell it otherwise.

        ts

        As a heads up, when using , your dependencies may need to be updated to use as well.

        No Implicit for

        When you use the keyword outside of classes, it has the type by default. For instance, imagine a class, and imagine a function that we wish to add as a method:

        ts

        This has the same problems we mentioned above - we could easily have misspelled and not gotten an error. For this reason, TypeScript has the option. When that option is set, TypeScript will issue an error when is used without an explicit (or inferred) type. The fix is to use a -parameter to give an explicit type in the interface or in the function itself:

        ts

        Sours: https://www.typescriptlang.org/docs/handbook/migrating-from-javascript.html
        React and TypeScript - Getting Started

        Adding TypeScript

        Note: this feature is available with and higher.

        TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.

        Installation#

        To start a new Create React App project with TypeScript, you can run:

        npx create-react-app my-app --template typescript

        # or

        yarn create react-app my-app --template typescript

        If you've previously installed globally via , we recommend you uninstall the package using or to ensure that always uses the latest version.

        Global installs of are no longer supported.

        To add TypeScript to an existing Create React App project, first install it:

        npm install --save typescript @types/node @types/react @types/react-dom @types/jest

        # or

        yarn add typescript @types/node @types/react @types/react-dom @types/jest

        Next, rename any file to be a TypeScript file (e.g. to ) and restart your development server!

        Type errors will show up in the same console as the build one. You'll have to fix these type errors before you continue development or build your project. For advanced configuration, see here.

        Getting Started with TypeScript and React#

        You are not required to make a file, one will be made for you. You are allowed to edit the generated TypeScript configuration.

        Troubleshooting#

        If your project is not created with TypeScript enabled, npx may be using a cached version of . Remove previously installed versions with or (see #).

        If you are currently using create-react-app-typescript, see this blog post for instructions on how to migrate to Create React App.

        Constant enums and namespaces are not supported, you can learn about the constraints of using Babel with TypeScript here.

        Sours: https://create-react-app.dev/docs/adding-typescript

        Now discussing:

        When I first started learning TypeScript, one of the suggestions I often heard was, “convert one of your existing projects! It’s the best way to learn!” Soon after, a friend from Twitter offered to do just that — show me how to migrate a React app to TypeScript.

        The purpose of this article is to be that friend for you and help you migrate your own project to TypeScript. For context, I will be using pieces from a personal project which I migrated while going through this process myself.

        The Plan

        To make this process feel less daunting, we’ll break this down into steps so that you can execute the migration in individual chunks. I always find this helpful when taking on a large task. Here are all the steps we’ll take to migrate our project:

        1. Add TypeScript
        2. Add
        3. Start simple
        4. Convert all files
        5. Increase strictness
        6. Clean it up
        7. Celebrate

        NOTE: the most important step in this whole process is number 7. Although we can only get there by working through them in sequential order.

        1. Add TypeScript to the Project

        First, we need to add TypeScript to our project. Assuming your React project was bootstrapped with , we can follow the docs and run:

        or if you’re using :

        Notice we haven’t changed anything to TypeScript yet. If we run the command to start the project locally ( in my case), nothing should be different. If that’s the case, then great! We’re ready for the next step.

        2. Add the

        Before we can take advantage of TypeScript, we need to configure this via the . The simplest way for us to get started is to scaffold one using this command:

        This gets us some basics.

        We have not yet interacted with TypeScript. We have only taken the necessary actions to get things ready. Our next step is to migrate a file to TypeScript. With this, we can complete this step and move onto the next.

        3. Start with a Simple Component

        The beauty of TypeScript is that you can incrementally adopt it. We can start with a simple component for our first piece of this migration. For my project, I’m going to start with a Button component that looks like this:

        To properly convert this, we need to do two things:

        1. Change the file extension to
        2. Add the type annotation

        Since this component takes two props, we need to change a few things:

        Let’s double-check that things are still working by running the project to ensure we didn’t break anything. Notice, here will automatically detect the new changes and modify our for us! Voila! How beautiful is that?

        And if all is well, our project will remain in working condition. Give yourself a pat on the back! You’ve successfully migrated your first file to TypeScript. If we wanted to stop here, we could, but let’s push forward.

        4. Convert All Files

        The next step is to do what we did for step 3, but for all files in the project. If the project you’re migrating is rather large, I suggest doing this over multiple iterations. Otherwise, you may tire yourself out.

        During this step, you may need to add additional packages depending on what third-party libraries you’re using. For instance, I am using so I had to run to add the types as a .

        Here are some other things to keep in mind as you do this:

        • Suppress TypeScript errors by adding on the line before the error
        • If a file uses jsx (i.e. ), the file extension must be instead of
        • Run the project locally to make sure things are still working (they should be)

        After you’ve completed this step, the hard stuff is done! Our project will be in TypeScript, but we’ll need to increase the strictness to take advantage of the benefits.

        5. Increase Strictness

        Now we are ready to increase the strictness by enabling stricter rules in our . Thankfully, will inform us of any type errors while running our project locally. We will follow the process like so:

        1. enable rule
        2. start project locally
        3. fix errors

        And we will repeat this process for the following rules:

          I want to share a tip. If you find that something implicitly has the type and you’re not sure how to fix it in that moment, don’t. Create this and use it to hush the error:

          Our goal is to move forward quickly and go back later to fix these.

          This will bring a greater amount of type safety to our project. If you’d like to read more about compiler options, you can read about it in the TypeScript Handbook.

          Once we’ve done this, we can then replace these:

            with this:

            which also enables these strict options:

            • strictBindCallApply
            • strictNullChecks
            • strictFunctionTypes
            • strictPropertyInitialization

            At this point, we have reached a standard level of strictness in our project. If we want to add additional checks, we can add these rules:

              Once we’ve reached a level of strictness that we’re happy with, we can proceed to the next step.

              6. Clean Up Shortcuts

              If you added or took advantage of a type, now is the time to go back and fix them. We don’t have to do these all at once, or ever, but this would be the last step to ensure maximum type safety across your project.

              Sometimes the effort to fix these is not worth the time, and other times it is. You’ll have to discuss with your team and decide what makes sense.

              7. Celebrate

              We did it! We officially migrated our project to TypeScript. Take a moment to celebrate your work. It was certainly not a trivial task. Especially if you were working in a large codebase.

              Things to Remember

              As we reflect on our efforts, here are some things to remember when migrating a project from React to TypeScript.

              Start Small

              Take advantage of TypeScript’s ability to gradually adopt it. Go one file at a time at your own pace. Do what makes sense for you and your team. Do not try to tackle it all at once.

              Increase Strictness Over Time

              There is no need to start with maximum strictness from the beginning. It is a journey. Increase the level as you have time. Eventually, you will reach a level that feels comfortable. Do not feel bad if you do not have % strictness. Some type safety is better than no type safety.

              Lean on Shortcuts

              The and the tip for are there to help lessen the burden of the migration. Not everything needs to changed at once. Use the shortcuts as you need but do not feel bad for using them. Again, the point is to migrate, but it should not be painful. Over time, you can prioritize replacing these things with proper type safety. But remember, these tools are at your disposal so use them.

              This is not the only approach for migrating React projects to TypeScript. However, it is what works for me. I hope it helps you as much as it helped me.

              Further Reading

              Updated on June 10,
              Special thanks to Karl Horky who reached out explaining that the `React.FC` type is not recommended because it provides almost no benefit and it has some downsides. See this GitHub discussion for more information.

              Sours: https://www.sitepoint.com/how-to-migrate-a-react-app-to-typescript/


              1966 1967 1968 1969 1970