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. 扩展性强:泛型接口支持不同支付渠道的差异化需求
相关推荐
可触的未来,发芽的智生12 小时前
新奇特:黑猫警长的纳米世界,忆阻器与神经网络的智慧
javascript·人工智能·python·神经网络·架构
悟乙己12 小时前
MLops | 基于AWS Lambda 架构构建强大的机器学习(ML)血缘关系
机器学习·架构·aws
007php00712 小时前
百度面试题解析:微服务架构、Dubbo、Redis及其一致性问题(一)
redis·百度·docker·微服务·容器·职场和发展·架构
尘世中一位迷途小书童18 小时前
版本管理实战:Changeset 工作流完全指南(含中英文对照)
前端·面试·架构
尘世中一位迷途小书童18 小时前
VitePress 文档站点:打造专业级组件文档(含交互式示例)
前端·架构·前端框架
m0_6515939119 小时前
Netty网络架构与Reactor模式深度解析
网络·架构
xrkhy1 天前
微服务之SpringCloud Alibaba(注册中心Nacos)
spring cloud·微服务·架构
虫小宝1 天前
Java分布式架构下的电商返利APP技术选型与架构设计实践
java·分布式·架构
唐僧洗头爱飘柔95271 天前
【SpringCloud(6)】Gateway路由网关;zuul路由;gateway实现原理和架构概念;gateway工作流程;静态转发配置
spring·spring cloud·架构·gateway·请求转发·服务降级·服务雪崩
白衣鸽子1 天前
RPO 与 RTO:分布式系统容灾的双子星
后端·架构