관리 메뉴

Silver Library (Archived)

How to implement typescript to the existing react app? 본문

F4. Library of Languages/TypeScript (TS)

How to implement typescript to the existing react app?

Chesed Kim 2023. 1. 25. 21:29
반응형

Suppose you installed react with npx create-react-app and install typescript on it as well.

And you need a quick solution of it.

 

Here is how I did.

 

  1. npm install --save typescript @types/node @types/react @types/react-dom @types/jest
  2. Add tsconfig.json with tsc --init
  3. Modify App.js and index.js to tsx.
  4. You will see errors. This means you need to define types for its error to be removed. Index.tsx will ask you to define something about const root. This means getElementById is the thing where the error occurred. In this case, 

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);

 

Will resolve the typescript error, by adding HTMLElement (getElementById is).



When working with TypeScript, it is important to understand the types of the values that you are working with in order to write correct and safe code.

 

In the case of the createRoot method from the ReactDOM module, the TypeScript type definition for this method specifies that it expects a single argument of type React.ReactElement.

 

createRoot<P>(

    container: React.ReactInstance,

    options?: { hydrate?: boolean; hydrationOptions?: HydrationOptions }

): ReactRoot<P>;

 

The document.getElementById method, on the other hand, returns an HTMLElement which is a type that represents a standard HTML element in the DOM.

 

getElementById(elementId: string): HTMLElement | null;

 

So, in this case, the type of the element returned by document.getElementById is HTMLElement, which is not the same as the expected type React.ReactElement for the createRoot method.

 

You can cast the returned value to the expected type by using the as operator, as you have done in your previous example, to tell the TypeScript compiler that the returned value is of a specific type (HTMLElement) and is compatible with the expected type (React.ReactElement).

 

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);

 

It's also a good idea to check the official documentation and other resources for more detailed information on the types and methods used in your code.

 

You may not be aware of what createRoot does. Now, you know it at glance, at least.

 

Be sure to import React to App.tsx. Once it is done, restart the webpack server. And you should be alright.