引言
随着前端技术的发展,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);
}
}
五、核心价值总结
- 类型安全:通过强类型避免支付金额、订单号等关键参数错误
- 接口清晰:明确的请求/响应定义降低集成成本
- 扩展性强:泛型接口支持不同支付渠道的差异化需求