
配置 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/**/*"]
}

被折叠的 条评论
为什么被折叠?



