# TypeScript 与前端框架整合

URL: https://caijiao.org/ts/part3/framework-integration
Source: docs/ts/part3/framework-integration.md
Description: 如何将 TypeScript 与常见前端框架（如 Vue 和 React）进行整合，涵盖了在框架中使用 TypeScript 的基本方法、配置以及类型推导。

[TypeScript](/ts/) 与前端框架的整合使得开发过程中可以享受类型安全和智能提示，提升了开发效率和代码可维护性。我们将讨论如何在 Vue 和 React 中使用 TypeScript。

## 在 Vue 项目中使用 TypeScript

Vue 3 支持 TypeScript，利用 Vue 的单文件组件（SFC）和 `defineComponent` API，可以方便地在 Vue 项目中使用 TypeScript。

### 安装 TypeScript 和相关工具

首先，确保你的 Vue 3 项目中安装了 TypeScript：

```bash
npm install typescript vue-tsc
```

然后，创建 `tsconfig.json` 配置文件，并确保将 `jsx` 设置为 `preserve`。

### 在单文件组件中使用 TypeScript

在 `.vue` 文件中，可以使用 `<script lang="ts">` 来启用 TypeScript。

```vue
<template>
  <div>{{ message }}</div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  data() {
    return {
      message: "Hello TypeScript!",
    };
  },
});
</script>
```

### 类型推导

Vue 3 的 `defineComponent` 自动提供类型推导，无需显式声明类型。

```ts
export default defineComponent({
  data() {
    return {
      count: 0,
    };
  },
  methods: {
    increment() {
      this.count++;
    },
  },
});
```

## 在 React 项目中使用 TypeScript

React 也提供了对 TypeScript 的强力支持，帮助我们更好地管理组件的类型和状态。

### 安装 TypeScript 和相关工具

对于一个新的 React 项目，可以通过 `create-react-app` 配置 TypeScript：

```bash
npx create-react-app my-app --template typescript
```

如果是现有项目，使用以下命令安装 TypeScript 及类型定义：

```bash
npm install typescript @types/react @types/react-dom
```

### 使用 TypeScript 编写 React 组件

在 React 中，函数组件和类组件都可以使用 TypeScript 来增强类型推导。

#### 函数组件

```tsx
import React, { FC } from "react";

interface Props {
  name: string;
  age?: number;
}

const Hello: FC<Props> = ({ name, age = 18 }) => {
  return (
    <div>
      Hello, {name}! Age: {age}
    </div>
  );
};
```

#### 类组件

```tsx
import React, { Component } from "react";

interface Props {
  name: string;
}

interface State {
  count: number;
}

class Counter extends Component<Props, State> {
  state: State = { count: 0 };

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <h1>{this.props.name}</h1>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>Increment</button>
      </div>
    );
  }
}
```

### JSX 类型声明

TypeScript 对 JSX 元素提供了类型支持，确保我们在 JSX 中使用的元素符合类型定义。

```tsx
const element: JSX.Element = <div>Hello TypeScript</div>;
```

在 React 和 Vue 中集成 TypeScript，不仅提高了代码的类型安全性，还使得自动完成功能更加高效，减少了运行时错误。
