当前位置: 首页 > article >正文

TypeScript 类型声明

在 TypeScript 开发中简化类型声明,可以通过以下 7 种实用技巧 显著提升效率:


一、善用类型推断(30% 场景免声明)

// ❌ 冗余写法
const user: { name: string; age: number } = { name: 'Jack', age: 25 };

// ✅ 自动推断(hover 变量可见类型)
const user = { name: 'Jack', age: 25 }; 

二、实用类型工具(20% 代码量)

类型工具应用场景示例
Partial<T>所有属性变为可选type Draft = Partial<Article>;
Pick<T, K>选取部分属性type Preview = Pick<Article, 'title'>
Omit<T, K>排除指定属性type SafeUser = Omit<User, 'password'>
ReturnType<T>获取函数返回值类型type Result = ReturnType<typeof fetch>
Record<K, T>快速定义键值类型type Pages = Record<string, React.FC>

三、类型守卫简化逻辑(if 判断即类型)

// 自定义类型守卫
function isAdmin(user: User): user is AdminUser {
  return 'privileges' in user;
}

// 使用示例
const handleUser = (user: User) => {
  if (isAdmin(user)) {
    user.manageSystem(); // 自动识别为 AdminUser 类型
  }
}

四、模块化类型管理

types/
├── user.d.ts        # 用户相关类型
├── api.d.ts         # API 响应类型
└── utils.d.ts       # 工具类型
// user.d.ts
export type UserRole = 'admin' | 'user';

export interface BaseUser {
  id: string;
  name: string;
  role: UserRole;
}

五、泛型优化重复代码

// 通用响应类型
interface ApiResponse<T = unknown> {
  code: number;
  data: T;
  message?: string;
}

// 使用示例
type UserResponse = ApiResponse<User>;
type ListResponse = ApiResponse<User[]>;

六、第三方类型工具库

  1. Zod (运行时类型校验)

    import { z } from "zod";
    
    const UserSchema = z.object({
      name: z.string(),
      age: z.number().positive()
    });
    
    type User = z.infer<typeof UserSchema>; // 自动推断类型
    
  2. TypeFest (高级工具类型)

    import type { CamelCase } from 'type-fest';
    
    type ApiResponse = {
      user_name: string;
      total_count: number;
    };
    
    type FrontendData = {
      [K in keyof ApiResponse as CamelCase<K>]: ApiResponse[K];
    };
    // { userName: string; totalCount: number }
    

七、IDE 高效开发技巧

  1. 快速修复
    在类型错误处按 Ctrl+. 自动生成类型声明

  2. 智能提示
    输入 user. 自动显示所有可用属性和方法

  3. 类型跳转
    Ctrl+Click 跳转到类型定义

  4. 重命名重构
    F2 安全修改类型名称(自动更新所有引用)


八、框架最佳实践

React 组件 Props
// 使用 interface 自动提示
interface ButtonProps {
  variant?: 'primary' | 'secondary';
  children: React.ReactNode;
}

const Button: React.FC<ButtonProps> = ({ variant = 'primary', children }) => (
  <button className={`btn-${variant}`}>{children}</button>
);
Vue Composition API
// 自动推断 ref 类型
const count = ref(0); // Ref<number>
const user = ref<User>(); // Ref<User | undefined>

九、处理第三方库类型

  1. DefinitelyTyped

    npm install --save-dev @types/lodash
    
  2. 框架内置类型

    // Next.js 页面 Props
    import type { GetServerSideProps } from 'next';
    
    export const getServerSideProps: GetServerSideProps = async () => {
      // ...
    }
    

十、终极简化方案

// 使用 satisfies 运算符(TS 4.9+)
const routes = {
  home: '/',
  about: '/about'
} satisfies Record<string, string>;

type Routes = keyof typeof routes; // "home" | "about"

通过结合这些技巧,可使 TypeScript 开发效率提升 50% 以上。核心原则是:让类型系统为你工作,而不是对抗它


http://www.kler.cn/a/568978.html

相关文章:

  • 【Python机器学习】1.1. 机器学习(Machine Learning)介绍
  • LeetCodeHot100_0x03
  • 分类预测 | Matlab实现GWO-LSSVM灰狼算法优化最小二乘支持向量机多特征分类预测
  • 商城系统单商户开源版源码
  • tableau之标靶图、甘特图和瀑布图
  • 计算机毕业设计SpringBoot+Vue.js校园失物招领系统(源码+文档+PPT+讲解)
  • 开源电商项目、物联网项目、销售系统项目和社区团购项目
  • 牛客刷题自留-深度学习
  • 云原生网络篇——万级节点服务网格与智能流量治理
  • Vue 系列之:基础知识
  • 重构MVC
  • 一次连接,可能会多次创建socket???
  • 心智模式与企业瓶颈突破
  • 基于 Ray 构建的机器学习平台
  • MATLAB的msgbox函数使用教程(一)
  • Java 泛型(Generics)详解与使用
  • FPGA开发,使用Deepseek V3还是R1(2):V3和R1的区别
  • git命令学习记录
  • IMX6Ull学习笔记1:汇编点亮LED灯
  • 【智能音频新风尚】智能音频眼镜+FPC,打造极致听觉享受!【新立电子】