TypeScript支付接口类型定义最佳实践

引言

随着前端技术的发展,TypeScript在支付系统开发中的应用越来越广泛。良好的类型定义能够提高代码的可维护性、可读性和健壮性,减少潜在的类型错误。本文将分享TypeScript在支付接口开发中的类型定义最佳实践,包括接口设计、类型推断、泛型应用、错误处理等方面的技巧和经验。

TypeScript支付接口类型定义最佳实践

一、核心类型设计

1.1 基础类型定义

ini 复制代码
// 金额类型(品牌类型确保类型安全)
type Amount = number & { __brand: 'Amount' };
// 订单号类型
type OrderId = string & { __brand: 'OrderId' };

// 支付状态枚举
enum PaymentStatus {
  PENDING = 'pending',
  SUCCESS = 'success',
  FAIL = 'fail'
}

// 支付渠道枚举
enum PaymentChannel {
  ALIPAY = 'alipay',
  WECHAT = 'wechat'
}

1.2 类型工厂函数

javascript 复制代码
// 创建金额(确保正数且保留两位小数)
function createAmount(value: number): Amount {
  if (value < 0) throw new Error('金额不能为负数');
  return Math.round(value * 100) / 100 as Amount;
}

// 创建订单号(确保格式正确)
function createOrderId(value: string): OrderId {
  if (!/^ORDER_\d{10,20}$/.test(value)) throw new Error('订单号格式错误');
  return value as OrderId;
}

二、支付接口定义

2.1 请求/响应接口

css 复制代码
// 基础支付请求接口
interface PaymentRequest {
  orderId: OrderId;
  amount: Amount;
  channel: PaymentChannel;
  subject: string;
  extra?: Record<string, any>; // 渠道额外参数
}

// 支付响应接口
interface PaymentResponse {
  success: boolean;
  data?: {
    paymentId: string;
    status: PaymentStatus;
    payUrl?: string; // 支付链接
  };
  error?: {
    code: string;
    message: string;
  };
}

2.2 泛型接口扩展

typescript 复制代码
// 带渠道参数的支付请求
interface ChannelPaymentRequest<T = Record<string, any>> extends Omit<PaymentRequest, 'extra'> {
  extra?: T;
}

// 支付宝额外参数
interface AlipayExtra {
  returnUrl?: string;
  notifyUrl?: string;
}

// 微信额外参数
interface WechatExtra {
  openId?: string;
}

// 渠道支付请求类型
type AlipayRequest = ChannelPaymentRequest<AlipayExtra>;
type WechatRequest = ChannelPaymentRequest<WechatExtra>;

三、类型守卫与错误处理

3.1 类型守卫函数

kotlin 复制代码
// 判断支付是否成功
function isPaymentSuccess(res: PaymentResponse): res is PaymentResponse & { success: true; data: NonNullable<PaymentResponse['data']> } {
  return res.success && !!res.data;
}

3.2 错误类型定义

scala 复制代码
// 支付错误基类
class PaymentError extends Error {
  code: string;
  constructor(message: string, code: string) {
    super(message);
    this.code = code;
  }
}

// 参数错误
class InvalidParamsError extends PaymentError {
  constructor(message: string) {
    super(message, 'INVALID_PARAMS');
  }
}

四、使用示例

javascript 复制代码
// 创建支付宝支付请求
const request: AlipayRequest = {
  orderId: createOrderId(`ORDER_${Date.now()}`),
  amount: createAmount(99.99),
  channel: PaymentChannel.ALIPAY,
  subject: 'TypeScript支付测试',
  extra: { notifyUrl: 'https://example.com/notify' }
};

// 处理支付响应
async function handlePayment() {
  const response = await paymentService.createPayment(request);
  if (isPaymentSuccess(response)) {
    console.log('支付成功:', response.data.payUrl);
  }
}

五、核心价值总结

  1. 类型安全:通过强类型避免支付金额、订单号等关键参数错误
  2. 接口清晰:明确的请求/响应定义降低集成成本
  3. 扩展性强:泛型接口支持不同支付渠道的差异化需求
相关推荐
Cerrda18 小时前
开发体验升级:UnoCSS 自定义 SVG 图标热更新方案
架构·前端框架
Kstheme1 天前
把任何 GitHub 仓库变成系统设计课:这个开源项目做到了
架构
禅思院1 天前
路由性能高可用架构实战方案
前端·架构·前端框架
贵慜_Derek2 天前
《从零实现 Agent 系统》连载 32|闭集 IE 与小模型:分类、意图与字段抽取
人工智能·架构·agent
江米小枣tonylua2 天前
译:设计生产级 RAG 架构
架构
怕浪猫3 天前
领域特定语言(Domain-Specific Language, DSL)
设计模式·程序员·架构
怕浪猫3 天前
哪些软件对 Chrome DevTools Protocol 频繁使用
人工智能·架构·前端框架
Jack203 天前
HarmonyOS APP事件驱动大揭秘
架构
Colin草率地做慢慢地改3 天前
关于QuickStore这个项目的重构(2)- 数据库建表文件
后端·面试·架构
candyTong3 天前
RTK 技术原理:一次典型会话里,80% 上下文是怎么省下来的
javascript·后端·架构