Skip to main content

TypeScript

The ZenPays SDK is written in TypeScript and provides full type safety.

Type Imports

Import types alongside runtime exports:

import type { Customer, PaymentIntent, Transaction } from 'zenpays'
import {

ZenPays
} from 'zenpays'

Or import types from the types subpath:

import type {
CreatePaymentIntentRequest,
Customer,
PaymentIntent,
} from 'zenpays/types'

Type-Safe API Calls

All API methods are fully typed:

const zenpays = new ZenPays({ apiKey: 'xxx' })

// Request type is inferred
const intent = await zenpays.payments.createPaymentIntent({
amount: 1000,
currency: 'USD',
// TypeScript will error if you miss required fields
})

// Response type is PaymentIntentResponse
console.log(intent.intentId) // string
console.log(intent.status) // PaymentStatus

Generic Response Types

Paginated responses use generics:

import type { PaginatedResponse, Transaction } from 'zenpays'

const result: PaginatedResponse<Transaction>
= await zenpays.payments.listTransactions()

result.data // Transaction[]
result.total // number
result.page // number

Discriminated Unions

Status types use discriminated unions for type narrowing:

const result = await zenpays.payments.confirmPayment('pi_xxx', { ... })

if (result.nextAction?.type === 'redirect') {
// TypeScript knows redirectUrl exists
window.location.href = result.nextAction.redirectUrl!
} else if (result.nextAction?.type === 'three_ds') {
// TypeScript knows threeDsUrl exists
handle3DSecure(result.nextAction.threeDsUrl!)
}

Error Types

Error classes are also typed:

import {
ZenPaysError,
ValidationError,
RateLimitError,
} from 'zenpays'

try {
await zenpays.payments.createPaymentIntent({ ... })
} catch (error) {
if (error instanceof ValidationError) {
// TypeScript knows about .fields
console.log(error.fields)
} else if (error instanceof RateLimitError) {
// TypeScript knows about .retryAfter
console.log(error.retryAfter)
}
}

Utility Types

The SDK exports utility types:

import type {
Currency,
PaymentMethodType,
PaymentStatus,
RiskLevel,
} from 'zenpays'

// Use in your own types
interface Order {
id: string
paymentStatus: PaymentStatus
paymentMethod: PaymentMethodType
currency: Currency
}

Configuration Types

import type { ZenPaysConfig } from 'zenpays'

// Type-safe configuration
const config: ZenPaysConfig = {
apiKey: process.env.ZENPAYS_API_KEY!,
timeout: 30000,
}

Strict Mode

The SDK works best with strict TypeScript settings:

{
"compilerOptions": {
"strict": true,
"strictNullChecks": true
}
}