What is Multi-Sample TypeScript Interface Inference?
TypeScript interfaces are essential for fullstack type safety. However, converting a single static JSON API response into TypeScript interfaces using online tools often leads to incorrect type declarations in production.
A single API payload sample cannot reveal fields that are conditionally present (e.g. admin-only properties) or fields that return null or alternative data types under specific user states.
Limitations of Single-Sample Tools
- Missed Optional Properties: Fields missing from the single sample are declared as mandatory, causing runtime
TypeError: Cannot read property of undefined. - Missing Union Types: Fields returning
stringin sample 1 butnumberornullin sample 2 are incorrectly hardcoded as a single rigid type. - Empty Array Degeneration:
"items": []in a single sample forces generators to default toany[]ornever[].
Multi-Sample Merging Algorithm
When provided with 2 or more JSON payload samples representing different business states, the inference engine executes the following logic:
- Field Frequency Tracking: If a property key exists in sample 1 but is omitted in sample 2, it is assigned the optional flag (
key?: Type). - Type Conflict Resolution: If sample 1 returns
stringand sample 2 returnsnull, the inferred type becomes a union:string | null. - Nested Object Merging: Sub-objects are merged recursively so all child attributes across samples are preserved.
// TypeScript output generated from 2 API samples:
export interface UserProfile {
id: number;
username: string;
email?: string | null; // Optional & nullable inferred from multi-sample comparison!
roles: string[];
bio?: string;
}Frequently Asked Questions (FAQ)
Q1: Why does single-sample JSON-to-TS inference fail in production?
Single API responses only represent a single snapshot of data. Optional fields or nullable attributes that appear under edge cases will be missed, causing runtime crashes when client code accesses un-declared optional properties.
Q2: How does the inference tool determine whether a field should have a question mark (?)?
If a key is missing in at least one of the provided payload samples (and the "Infer Optional Properties" option is enabled), the tool automatically adds ? to that property name in the generated interface.
Q3: Can I customize the root interface name and empty array fallback type?
Yes! You can specify the root interface name (e.g. ApiResponse or UserData) and set the empty array fallback type to unknown[] or any[].