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. 扩展性强:泛型接口支持不同支付渠道的差异化需求
相关推荐
keeper_zdl8 小时前
GitLabCI/CD自动化构建与联调实战
python·架构
zkmall9 小时前
电商高并发稳赢指南:ZKmall开源商城微服务架构的实战拆解
微服务·架构·开源
brzhang10 小时前
Google 浏览器出了一个超级好用的功能,Gemini 原生支持,帮你解决性能问题
前端·后端·架构
洛卡卡了10 小时前
适配私有化部署,我手写了套支持离线验证的 License 授权系统
java·后端·架构
铅笔侠_小龙虾11 小时前
大话 IOT 技术(1) -- 架构篇
物联网·架构
数据智能老司机11 小时前
探索 Kafka 主题与消息
架构·kafka·消息队列
数据智能老司机11 小时前
kafka的性能
架构·kafka·消息队列
brzhang12 小时前
现在有一种深深的感觉,觉大多数情况下,多 Agent 不如单 Agent 好
前端·后端·架构