Skip to main content

Precise Integer and Float Validation in TypeScript v4 SDKs

· 2 min read

TypeScript v4 SDKs now check numbers by the kind your specification declares rather than accepting any number for every numeric field.

Details​

Every numeric field is still typed number, and its schema decides which check runs. An integer field, whether int32, int64 or type: integer with no format, is checked with s.int(), which rejects a fraction and any value outside JavaScript's safe-integer range. A float, a double, a big decimal or type: number with no format is checked with s.float64(), which rejects NaN and ±Infinity.

An int64 larger than Number.MAX_SAFE_INTEGER is rejected rather than silently rounded. A request value that fails its check rejects the call with an EncodeError before anything is sent, and a response value that fails rejects with a DecodeError.

Usage Example​

A value the specification types as an integer is checked before the request leaves:

import { PaymentsClient, PaymentsError } from "payments";

const client = new PaymentsClient();

try {
// quantity is an integer in the specification, so 2.5 is rejected.
await client.orders.create({ body: { sku: "SKU-1", quantity: 2.5 } });
} catch (err) {
if (err instanceof PaymentsError && err.kind === "encode") {
console.error("Nothing was sent:", err.cause);
} else {
throw err;
}
}

The cause is the SchemaError that names the field and the check it failed.

This feature is available in the TypeScript v4 SDK. Generate it with version 2.x of the APIMatic CLI:

apimatic sdk generate --language=typescript

For the full set of flags and options, see the APIMatic CLI documentation.