swift-typescript-bridge: The Swift Macro That Makes TypeScript Unions Feel Native

A close look at the macro tricks, discriminator fast path, and literal-union decoding that let Swift mirror TypeScript schemas with far less boilerplate.

8 min read • View on GitHub • More from sunghyun-k

A wide editorial scene shows two workspaces facing each other. On the left, a compact TypeScript schema sheet with union types sits beside a clean keyboard. On the right, a Swift desk is crowded with Codable boilerplate, enum cases, and decoder branches. A narrow bridge of generated macro tokens spans the gap between them, showing how the project turns a language mismatch into a compile-time transformation.
The library does not just translate types. It compresses the friction between two type systems into one generated bridge.
Key Takeaways

The best way to understand swift-typescript-bridge is to start with the part Swift usually makes painful: unions. TypeScript is happy to say a field can be "auto" | 100 or one of several object shapes. Swift usually answers with a long enum, custom decoding logic, and a lot of repetition.

This repo does not pretend that mismatch disappears. It does something better. It moves the mismatch into a macro, then generates the enum, the decoding paths, and the discriminator-aware shortcuts for you.

The union problem Swift never solved

TypeScript unions are expressive because they are cheap to write and easy to compose. Swift can model the same ideas, but the ceremony piles up fast. If you want a value that might be one of several literals, or one of several payload types, you usually end up building the shape yourself and teaching Codable how to walk it.

That is tolerable once. It is exhausting across an API surface. The appeal of this project is that it turns a schema translation problem into a declaration problem.

@Union("auto", "manual")
enum Mode {}

@Union(User.self, Org.self)
enum Actor {}
A close editorial scene contrasts a messy stack of handwritten Swift enum cases and decode branches with a compact generated union declaration. One side shows multiple pages of boilerplate crossing out repeated code, while the other side shows a single macro declaration that expands into the same structure. The image explains how the library compresses repetitive Swift modeling into one source-level annotation.
The macro does not remove the model. It removes the repetition around the model.

How @Union compresses boilerplate into one declaration

The public surface is small on purpose. The library defines a literal-boundary protocol, then lets the macro generate the cases and decoding behavior for supported literal types like String, Int, Double, and Bool. That keeps the API opinionated instead of magical.

The mixed-union path is the clever bit. When the macro sees something like @Union("auto", 100), it can generate a single enum that stores a raw value through an existential literal type, then tries the right concrete representation at decode time.

public protocol _LiteralType {}

extension String: _LiteralType {}
extension Int: _LiteralType {}
extension Double: _LiteralType {}
extension Bool: _LiteralType {}

That small boundary matters. It prevents the macro from drifting into a generic grab bag and forces the generated code to stay inside the types Swift can actually reason about.

The real trick: discriminator-aware decoding

The most interesting behavior in the repo is not the enum generation itself. It is the decoder path for structural unions. The library can recognize when a candidate type conforms to TypeDiscriminated, read a discriminator key, and jump directly to the right branch instead of trying every schema in sequence.

When a discriminator exists, the decoder can stop guessing and route straight to the right type.

That is the difference between a neat macro and a practical one. Sequential decoding is fine when you have two cases. It gets expensive, and brittle, when you have many. A discriminator gives the library a short-circuit, which is both faster and less error-prone.

Introducing swift-typescript-bridge, an open-source tool that automatically generates Swift code from TypeScript definitions. Bridging Swift and TypeScript has never been easier!

Sunghyun Kim, Project Creator · X/Twitter post by Sunghyun Kim

Why this is faster than naive trial-and-error decoding

The fallback path still matters. Not every union will carry a clean discriminator, and not every type should be forced into one. When the tag is missing, the library can still fall back to sequential decode attempts using a single-value container.

ApproachInput sourceUnion supportDecoder strategySwift ergonomicsBest fit
Manual Codable boilerplateHandwritten SwiftYes, but customUsually trial-and-error or custom branchingVerboseSmall one-off models
swift-typescript-bridgeTypeScript definitionsYes, including mixed literalsDiscriminator fast path plus fallbackMacro-generatedShared TS to Swift schemas
QuickTypeJSON or schemaPartial, depends on schema shapeGenerated parsing codeGood, but broader and less TS-specificGeneral codegen
Language-level interopFuture toolchain supportPotentially nativeToolchain-definedBest long term, not here yetPlatform evolution

That tradeoff is the heart of the project. It does not force every schema into the fastest path. It makes the fast path available when the source type supports it, then preserves a sane fallback when it does not.

What it is competing with

This repo sits in a narrow but useful lane. Manual Codable code gives you full control, but costs time. Generators like QuickType help, but they are broader tools. Larger interop efforts may eventually reduce the need for a bridge like this, but they are not the same thing as a working macro today.

That is why the project feels specific in a good way. It is optimized for one boring, expensive job: keeping Swift aligned with TypeScript schemas without making developers pay the boilerplate tax over and over.

Why the project feels unusually polished for its size

The codebase shows that the author cared about the edge cases that usually get ignored. Access modifiers propagate correctly, tests cover numeric and literal behavior, and the macro layer is separated cleanly from the public API.

The dependency surface is also small. That matters for a macro package, because every extra dependency increases the chance that the toolchain becomes the real product. Here, the product stays simple: SwiftSyntax, Swift 6.2, and a focused set of transformations.

Origin and intent

Sunghyun Kim introduced the project as a way to automatically generate Swift code from TypeScript definitions. That framing is useful because it keeps the story honest. This is not a new type system. It is a bridge for teams that already made TypeScript the source of truth.

The project exists because the cost of retyping schemas is higher than it looks. Once a team has both a TypeScript backend or contract layer and a Swift consumer, the real bug risk is drift. This repo attacks that drift directly.