React 和 TypeScript 是现代 web 开发中两个非常重要的工具,它们可以一起使用以提高代码质量和效率。以下是一些在使用 React 和 TypeScript 时的小结和示例代码:
- 安装 TypeScript 和相关类型定义:
 
npm install --save typescript @types/react @types/react-dom @types/node
- 配置 
tsconfig.json 文件,启用 JSX 支持: 
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src"]
}
- 创建一个简单的 TypeScript React 组件:
 
import React from 'react';
 
type MyComponentProps = {
  text: string;
};
 
const MyComponent: React.FC<MyComponentProps> = ({ text }) => {
  return <div>{text}</div>;
};
 
export default MyComponent;
- 在 
index.tsx 文件中使用该组件: 
import React from 'react';
import ReactDOM from 'react-dom';
import MyComponent from './MyComponent';
 
ReactDOM.render(<MyComponent text="Hello, TypeScript & React!" />, document.getElementById('root'));
- 确保 TypeScript 编译器能正确处理 
.js 和 .jsx 文件: 
// tsconfig.json
{
  "compilerOptions": {
    // ...
    "jsx": "react-jsx", // 这告诉 TypeScript 处理 JSX
  }
}
- 使用 TypeScript 接口定义复杂对象的类型:
 
interface User {
  id: number;
  name: string;
  email: string;
}
 
const user: User = {
  id: 1,
  name: 'John Doe',
  email: 'john@example.com',
};
- 使用 TypeScript 函数和类时进行类型注解和类型检查:
 
function sum(a: number, b: number): number {
  return a + b;
}
 
class Person {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
 
  greet(): string {
    return `Hello, ${this.name}!`;
  }
}
- 使用 TypeScript 的泛型来创建可复用的组件:
 
import React from 'react';
 
type BoxProps<T> = {
  value: T;
};
 
const Box = <T,>(props: BoxProps<T>) => {
  return <div>{props.value}</div>;
};
 
export default Box;
以上是一些在使用 TypeScript 和 React 时的常见场景和代码示例。通过这些实践,开发者可以在保持代码类型安全的同时,享受现代 web 开发带来的高效和乐趣。