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. 扩展性强:泛型接口支持不同支付渠道的差异化需求
相关推荐
yunteng5212 小时前
通用架构(同城双活)(单点接入)
架构·同城双活·单点接入
麦聪聊数据2 小时前
Web 原生架构如何重塑企业级数据库协作流?
数据库·sql·低代码·架构
程序员侠客行3 小时前
Mybatis连接池实现及池化模式
java·后端·架构·mybatis
bobuddy4 小时前
射频收发机架构简介
架构·射频工程
桌面运维家5 小时前
vDisk考试环境IO性能怎么优化?VOI架构实战指南
架构
一个骇客6 小时前
让你的数据成为“操作日志”和“模型饲料”:事件溯源、CQRS与DataFrame漫谈
架构
鹏北海-RemHusband7 小时前
从零到一:基于 micro-app 的企业级微前端模板完整实现指南
前端·微服务·架构
2的n次方_9 小时前
Runtime 内存管理深化:推理批处理下的内存复用与生命周期精细控制
c语言·网络·架构
前端市界10 小时前
用 React 手搓一个 3D 翻页书籍组件,呼吸海浪式翻页,交互体验带感!
前端·架构·github
文艺理科生10 小时前
Nginx 路径映射深度解析:从本地开发到生产交付的底层哲学
前端·后端·架构