Home / Companies / Speakeasy / Blog / Post Details
Content Deep Dive

Forward compatible unions in TypeScript

Blog post from Speakeasy

Post Details
Company
Date Published
Author
David Adler
Word Count
2,090
Language
English
Hacker News Points
-
Summary

Designing forward-compatible unions in TypeScript involves addressing challenges related to API evolution, especially when handling unknown variants in SDKs. A common problem arises when APIs introduce new providers or types, causing applications to crash if they cannot parse unexpected data. While proper API versioning could mitigate this, it is not always feasible, making forward-compatible client design a practical necessity. The article explores several strategies to handle this, emphasizing the importance of preserving type narrowing and gracefully managing new server responses. One effective approach uses a sentinel value like "UNKNOWN" to capture unknown variants while maintaining type safety, although it may introduce breaking changes if the API later adopts "UNKNOWN" as a legitimate value. The Speakeasy SDK generator employs this approach when a discriminator can be inferred, defaulting to a monadic wrapper for more complex polymorphic unions without common discriminators. Overall, the article highlights that while there are no perfect solutions, understanding the trade-offs of each method is crucial for building robust and forward-compatible SDKs.