Convert Fixed-Length JSON Arrays to TypeScript Tuples
Learn how to represent fixed-length JSON arrays as TypeScript tuple types instead of generic arrays. Preserve positional type information.
Detailed Explanation
Tuples vs Arrays in TypeScript
A regular TypeScript array (string[]) allows any number of elements of the same type. A tuple ([string, number]) specifies an exact number of elements with a type for each position.
Example JSON
{
"coordinates": [39.7817, -89.6501],
"range": [1, 100],
"nameAge": ["Alice", 30]
}
Generated TypeScript
interface Root {
coordinates: [number, number];
range: [number, number];
nameAge: [string, number];
}
Why Tuples Matter
Without tuples, coordinates would be typed as number[], which allows arrays of any length. Tuples enforce that there are exactly two elements, and nameAge preserves the fact that element 0 is a string and element 1 is a number.
Accessing Tuple Elements
TypeScript knows the type of each index:
const [lat, lng] = data.coordinates;
// lat: number, lng: number
const [name, age] = data.nameAge;
// name: string, age: number
When the Converter Chooses Tuples
The converter generates tuples when:
- The array has a fixed, small length (typically 2-5 elements).
- The elements have mixed types (e.g.,
[string, number]). - Multiple samples show the same length consistently.
If the length varies across samples, the converter falls back to a union array ((string | number)[]).
Labeled Tuples (TypeScript 4.0+)
You can add labels for documentation:
type GeoCoord = [lat: number, lng: number];
type NameAge = [name: string, age: number];
Labels do not affect type checking but significantly improve editor hover information and function signatures.
Optional Tuple Elements
type Response = [number, string, string?];
// 2 or 3 elements
This is useful when some API responses include an optional third element for extra details.
Use Case
You are working with a geolocation API that returns coordinates as two-element arrays, and you want TypeScript to enforce that exactly a latitude and longitude are present.
Try It — JSON to TypeScript
Related Topics
Convert JSON Arrays of Objects to TypeScript Types
Basic Conversions
Generate TypeScript Union Types from JSON String Values
Type Refinements
Convert a Simple JSON Object to a TypeScript Interface
Basic Conversions
Type a Full API Response JSON as TypeScript
Advanced Patterns
Generate Readonly TypeScript Interfaces from JSON
Advanced Patterns