For senior developers

End-to-end type safety between Go and TypeScript without GraphQL

A type annotation on the result of fetch is not a check. It is a promise you made to the compiler about bytes that arrive at runtime, and when the backend changes shape the compiler keeps believing you. The failure is a TypeError in a browser, at the line that read the field.

There are four honest ways to close this, none of which is GraphQL. The differences are about what you give up, not about which is cleverest.

18 min read. Commands and output last run against Grit v3.560.0.

What you will have at the end

A clear-eyed comparison of tygo, OpenAPI codegen, Connect and hand-written types.

A generated Zod schema as well as a TypeScript type, which is the part most setups leave out.

A check that fails CI when the two sides drift.

The thing that is not true

interface Invoice {
id: number
total: number
dueAt: string
}
const res = await fetch('/api/invoices/1')
const invoice: Invoice = await res.json() // zero checking happens here
invoice.dueAt.slice(0, 10)
// TypeError: Cannot read properties of undefined
// Because the API returns { data: { due_at: "..." } }, and
// camelCase, the envelope and the field name are all wrong.

res.json() returns any, and an annotation on any is an assertion. TypeScript's types are erased before the code runs, so nothing at runtime ever compares the shape to the declaration. Everything below is about removing the human step where those two can disagree.

The four options

1. Hand-written types

Free, immediate, and wrong within two sprints. Not because anybody is careless: a Go developer adds a field, the TypeScript file is in another directory, and nothing connects the two. Acceptable for a tiny API with one consumer and one author.

2. Generate types from Go structs (tygo, go2ts)

tygo.yaml
packages:
- path: "github.com/you/app/internal/models"
output_path: "packages/shared/types/models.ts"
type_mappings:
time.Time: "string"
uuid.UUID: "string"
decimal.Decimal: "string"

Cheap and effective: the Go struct is the single definition, and the TypeScript follows it. What it does not give you is the endpoint, the parameters or the error shapes, so the route and its response are still joined by hand. And it produces types only, not a runtime validator, so the gap in the first section is narrowed rather than closed.

3. OpenAPI, with generated clients

Describe the whole surface: routes, parameters, responses and errors. Generate a typed client from it, and generate clients for other languages from the same document.

The question is which direction it is generated. An OpenAPI document written by hand beside the code drifts like any other duplicate. Generated from annotations in the Go code, it cannot, and the annotations are then the thing to keep correct. The second is the only version worth doing.

Worth the machinery when you have third-party consumers, several client languages, or a published API. Heavy for one frontend you also own.

4. Connect, or gRPC-Web

Define the service in protobuf and generate both sides. The strongest guarantee here, by some distance: one definition produces the server interface and the client, and they cannot disagree because neither is written.

The cost is that your API is no longer plain JSON over REST. Debugging with curl changes, caching by URL changes, and every consumer needs a generated client. Connect mitigates much of this by speaking ordinary HTTP and JSON as well. The right answer for a service mesh; a large commitment for a web app and a mobile app.

The piece most setups leave out

Generated types tell the compiler what the API should return. Nothing checks what it did return. A deployed backend one version ahead, a proxy returning an error page, a field that became nullable: all produce data your types say is impossible.

import { z } from 'zod'
// Generated from the Go struct and its binding tags, so the validation
// matches the server's own rules rather than being a second opinion.
export const InvoiceSchema = z.object({
id: z.number(),
number: z.string().min(1).max(50),
total: z.number().int(),
status: z.enum(['draft', 'sent', 'paid']),
due_at: z.string().datetime(),
})
export type Invoice = z.infer<typeof InvoiceSchema> // one definition
// Parse at the boundary. Now a shape change is an error you can see and
// report, at the fetch, rather than an undefined three components away.
const body = await res.json()
const invoice = InvoiceSchema.parse(body.data)

Validate at the edge and only at the edge: once past the parse, the value genuinely has the type, and nothing downstream needs to check again. That is the difference between types that are true and types that are hoped for.

The same schema drives the form

The generated schema is also the form validator, so the rules in the browser are the rules the server enforces. The alternative, a hand-written form rule beside a generated type, is how a form accepts a value the API then rejects with a 422 nobody can explain.

The four places the two sides disagree

  • Naming. Go is PascalCase, JSON is often snake_case, and TypeScript conventions pull towards camelCase. Pick one for the wire and never convert in the middle. A generator should read the json tag rather than the field name, since the tag is what actually goes out.
  • Optional against nullable. Go's *string becomes string | null, and a field with omitempty becomes string | undefined. They are different, and a generator that treats them as one produces types that are wrong on exactly the fields that cause crashes.
  • Numbers. Go's int64 exceeds JavaScript's safe integer range, so a large id silently loses precision. Serialise those as strings, or know that your ids stay small.
  • Empty slices. A nil slice marshals to null, and with omitempty it marshals to no key at all. The frontend calls .filter on it and crashes. Initialise slices before returning them, and do not put omitempty on a list the client iterates. TypeScript cannot see this one, which is what makes it common.
// Wrong: an empty result sends no key, and the page crashes on
// .map of undefined.
type ListResponse struct {
Data []Invoice `json:"data,omitempty"`
}
// Right: always a key, always an array.
type ListResponse struct {
Data []Invoice `json:"data"`
}
func (s *Service) List(ctx context.Context) (*ListResponse, error) {
out := &ListResponse{Data: []Invoice{}} // not nil
...
}

Error shapes need generating too

Response types usually get generated and error types usually do not, so the frontend branches on a string it copied out of a handler once.

// Go: the codes as constants, which is what gets generated.
const (
ErrCodeValidation = "VALIDATION_ERROR"
ErrCodeNotFound = "NOT_FOUND"
ErrCodeDuplicateISBN = "DUPLICATE_ISBN"
)
// Generated from the same list. A code removed in Go becomes a type
// error in the frontend, instead of a branch that stops matching.
export const ErrorCode = {
Validation: 'VALIDATION_ERROR',
NotFound: 'NOT_FOUND',
DuplicateISBN: 'DUPLICATE_ISBN',
} as const
export type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode]

Branch on the code, never on the message. A message is for a person and will be rewritten by somebody improving the copy, at which point every client comparing against it breaks silently.

Make drift fail the build

A generator only helps if it has run. The check is one line and it is the thing that makes the whole arrangement reliable:

- name: types are current
run: |
grit sync # or: tygo generate
git diff --exit-code packages/shared/

Regenerate, and fail if anything changed. A pull request that alters a Go struct without the matching generated file cannot merge. Without this, generation is a thing people remember until they are in a hurry.

One writer per generated file

If both a generator and a human can edit packages/shared/types/, the generator will eventually overwrite somebody's change, or somebody will hand-fix a file that is regenerated on the next run. Mark generated files as generated, keep hand-written types in a different directory, and have one command that produces them all.

How Grit does it

Terminal
$grit sync

Reads the Go models and writes the TypeScript types, the Zod schemas and the error codes from them. The Go struct, with its json and binding tags, is the single definition: the tag decides the field name, and the binding rules become the Zod rules, so the browser enforces what the server enforces.

// Go
type Invoice struct {
ID uint `json:"id"`
Number string `json:"number" binding:"required,min=1,max=50"`
Total int64 `json:"total" binding:"gte=0"`
Status string `json:"status" binding:"oneof=draft sent paid"`
}
// Generated
export const InvoiceSchema = z.object({
id: z.number(),
number: z.string().min(1).max(50),
total: z.number().int().gte(0),
status: z.enum(['draft', 'sent', 'paid']),
})
export type Invoice = z.infer<typeof InvoiceSchema>

Two properties worth knowing. Generating a resource and running sync must leave no diff, which is tested, because two writers producing almost the same file is how a shared package starts disagreeing with itself. And project-specific error codes are declared in one file and folded into both the Go constants and the TypeScript union, so an undeclared code is caught rather than answering 500 quietly.

The shared package reference covers what is generated and what is yours.

Frequently asked questions

Why not GraphQL? It solves this.
It does, and it brings a schema language, a resolver layer, a query planner, N+1 problems that need DataLoader, caching that no longer works by URL, and an attack surface in arbitrary query depth. That is a reasonable trade when many clients need different shapes of the same data. For one frontend and one mobile app, generating types from the Go you already wrote achieves the same safety for a fraction of the machinery.
Are generated types enough, or do I need runtime validation?
Types alone are a compile-time agreement about runtime data, so they are enough right up until the two sides are on different versions, which is every deploy window. A runtime parse at the boundary turns that from an undefined deep in a component into an error at the fetch, with a message naming the field. The cost is a few microseconds per response.
tygo or OpenAPI?
tygo if the frontend is yours and you want types with near-zero ceremony. OpenAPI if you have external consumers, several client languages, or need documentation that is generated rather than written. Generate the document from annotations in the Go code; a hand-written OpenAPI file beside the code is one more thing that drifts.
What about int64 ids in JavaScript?
JavaScript numbers are doubles, so integers above 2^53 lose precision silently. A snowflake id or a large counter will eventually round, and the symptom is a lookup failing for one specific record. Serialise large integers as strings, and have the generator map int64 to string so the type system reminds everybody.

Next steps