项目整合实战:如何在 React/Vue 项目中配置并享受 TypeScript 的好处

配置 TypeScript 基础环境

在 React 项目中初始化 TypeScript:

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

在 Vue 项目中初始化 TypeScript:

vue create my-app # 手动选择 TypeScript 选项

或使用 Vite 快速搭建:

npm create vite@latest my-app -- --template vue-ts

类型定义与组件集成

React 函数组件类型标注:

interface Props {
  title: string;
  count: number;
}

const MyComponent: React.FC<Props> = ({ title, count }) => (
  <div>{title}: {count}</div>
);

Vue 3 组合式 API 类型标注:

<script setup lang="ts">
interface Props {
  msg: string;
}

const props = defineProps<Props>();
</script>

状态管理类型化

Redux 类型化示例:

interface CounterState {
  value: number;
}

const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 } as CounterState,
  reducers: {
    increment(state) {
      state.value += 1;
    }
  }
});

Vuex 类型化方案:

import { InjectionKey } from 'vue';

interface State {
  count: number;
}

export const key: InjectionKey<Store<State>> = Symbol();

export const store = createStore<State>({
  state: { count: 0 },
  mutations: {
    increment(state) {
      state.count++;
    }
  }
});

API 响应类型处理

定义并复用 API 类型:

interface User {
  id: number;
  name: string;
  email: string;
}

async function fetchUsers(): Promise<User[]> {
  const response = await fetch('/api/users');
  return response.json();
}

第三方库类型扩展

补充缺失的类型声明:

declare module 'untyped-library' {
  export function someFunction(input: string): number;
}

构建配置优化

tsconfig.json 关键配置项:

{
  "compilerOptions": {
    "strict": true,
    "jsx": "preserve",
    "baseUrl": "./src",
    "paths": {
      "@components/*": ["components/*"]
    }
  },
  "include": ["src/**/*"]
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值