Using TypeScript with React: Types, Generics, and Best Practices

This article explains how to integrate TypeScript with React, covering type definitions, generic components, event handling, utility types, and best practices such as using declaration files, avoiding any, and leveraging TypeScript’s advanced type utilities to improve code safety and developer productivity.

HomeTech
HomeTech
HomeTech
Using TypeScript with React: Types, Generics, and Best Practices

TypeScript is a superset of JavaScript that adds static typing, generics, namespaces, and enums, addressing the shortcomings of JavaScript in large‑scale applications. When combined with React, it provides strong type checking for components, props, and state.

Project setup can be done quickly with Facebook's create-react-app using the TypeScript template:

npx create-react-app my-app --scripts-version=react-scripts-ts

After installation, start the development server with npm start or yarn start.

First TSX component demonstrates importing React and defining a functional component:

import * as React from 'react';

const App: React.FC = () => {
  return <div>Hello world</div>;
};

export default App;

Stateful component shows how to define props and state with interfaces, making them strongly typed:

interface IProps {
  color: string;
  size?: string;
}

interface IState {
  count: number;
}

class App extends React.Component<IProps, IState> {
  public state: IState = { count: 1 };
  // ...render and lifecycle methods
}

TypeScript enforces read‑only props and state via the Readonly utility, preventing direct mutation such as this.state.count = 2, which would raise TS2540 errors.

Stateless functional component (SFC) can be typed using the built‑in SFC type:

import { SFC } from 'react';

interface IProps { onClick: (e: MouseEvent<HTMLDivElement>) => void; }

const Button: SFC<IProps> = ({ onClick, children }) => (
  <div onClick={onClick}>{children}</div>
);

export default Button;

Event handling benefits from React's typed event interfaces (e.g., MouseEvent, KeyboardEvent). Instead of using any, developers can type handlers precisely:

interface IProps {
  onClick: MouseEventHandler<HTMLDivElement>;
}

const Button: SFC<Partial<IProps>> = ({ onClick, children }) => (
  <div onClick={onClick}>{children}</div>
);

React also provides the EventHandler type alias, which abstracts the event generic E for cleaner signatures.

Promise typing shows how to declare a generic response interface and an async function returning Promise<IResponse<number[]>>:

interface IResponse<T> {
  message: string;
  result: T;
  success: boolean;
}

async function getResponse(): Promise<IResponse<number[]>> {
  return { message: '获取成功', result: [1, 2, 3], success: true };
}

getResponse().then(response => console.log(response.result));

Custom DOM attributes should use the data-* prefix to avoid TypeScript errors, e.g., <div data-value="123"></div>.

Utility generic tricks include using typeof to infer types, string/number literal types for constrained values, and built‑in utility types such as Partial<T>, Required<T>, Pick<T, K>, Record<K, T>, Exclude<T, U>, Extract<T, U>, Omit<T, K>, NonNullable<T>, and ReturnType<T>. Example of Omit implementation:

type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;

These utilities enable precise type manipulation, making React code safer and more maintainable.

Conclusion emphasizes reading declaration files, avoiding any, defining comprehensive types, and staying updated with TypeScript releases to leverage new features.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

TypeScriptReactGenericsUtility Typesevent-handling
HomeTech
Written by

HomeTech

HomeTech tech sharing

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.