Documentation
¶
Overview ¶
Package codegen generates TypeScript type definitions from Go source code.
It scans Go packages for tRPC procedure registrations (Query, Mutation, Subscription) and produces .d.ts files compatible with @trpc/client.
Parsing Strategies ¶
The package uses two parsing strategies with automatic fallback:
ParsePackage uses golang.org/x/tools/go/packages for full type resolution. This is the preferred path and produces the most accurate TypeScript types, including types from external packages.
ParseDir uses go/parser for AST-only extraction without type checking. This fallback handles cases where the Go toolchain cannot fully resolve types (e.g., missing dependencies). It extracts type names as strings and resolves struct definitions from AST.
Both strategies scan for gotrpc.Query(), gotrpc.Mutation(), and gotrpc.Subscription() call expressions in the AST, extract the procedure name (second argument) and handler type information (third argument), and resolve namespace prefixes from Router.Merge() calls.
Type Mapping ¶
Go types are mapped to TypeScript via TypeMapper:
string → string
int, float64 → number
bool → boolean
[]T → T[]
map[K]V → Record<K, V>
*T → T | null
struct{} → void
time.Time → string (ISO 8601)
enum patterns → union types ("active" | "inactive")
Output ¶
Generate produces either .d.ts (type declarations) or .ts (with runtime metadata). The output includes an AppRouter interface with nested namespaces matching the procedure hierarchy.
Index ¶
- func ConvertGoToTS(goCode string) (string, error)
- func Generate(opts GenerateOptions) error
- func GenerateFromProcedures(procedures []ProcedureInfo, routerName string) string
- func SchemaHandler(procedures []SchemaInfo) (http.HandlerFunc, error)
- type EnumInfo
- type GenerateOptions
- type MergeInfo
- type ParseResult
- type ProcedureInfo
- type SchemaInfo
- type SchemaResponse
- type StructDef
- type StructField
- type TSType
- type TypeMapper
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ConvertGoToTS ¶
ConvertGoToTS parses Go type declarations from source code and returns their TypeScript equivalents using the same TypeMapper used by the codegen CLI.
The input should contain Go type declarations (no package clause needed):
type User struct {
Name string `json:"name"`
Email string `json:"email"`
}
func Generate ¶
func Generate(opts GenerateOptions) error
Generate parses the Go source and generates the .d.ts file.
func GenerateFromProcedures ¶
func GenerateFromProcedures(procedures []ProcedureInfo, routerName string) string
GenerateFromProcedures generates a .d.ts string from pre-parsed procedure info.
func SchemaHandler ¶
func SchemaHandler(procedures []SchemaInfo) (http.HandlerFunc, error)
SchemaHandler returns an http.HandlerFunc that serves the introspection schema. It takes a list of procedure infos (typically from the router at startup).
Types ¶
type EnumInfo ¶
type EnumInfo struct {
TypeName string // the Go type short name (e.g., "Status")
QualifiedName string // fully qualified name (e.g., "example.com/models.Status")
Values []string // the const values (e.g., ["active", "inactive"])
IsString bool // true if underlying type is string, false if int
}
EnumInfo holds information about a Go enum pattern (type X string/int + const block).
type GenerateOptions ¶
type GenerateOptions struct {
OutputPath string
RouterName string // defaults to "AppRouter"
SourcePath string
Format string // "dts" (default) or "ts"
DryRun bool // print output to stdout instead of writing to disk
}
GenerateOptions configures the TypeScript generation.
type MergeInfo ¶
type MergeInfo struct {
ParentVar string // the router being merged into (e.g., "r")
Prefix string // the namespace prefix (e.g., "task")
ChildVar string // the router being merged (e.g., "taskRouter")
}
MergeInfo holds information about a router Merge() call.
type ParseResult ¶
type ParseResult struct {
Procedures []ProcedureInfo
Merges []MergeInfo
Enums []EnumInfo
StructDefs []StructDef
RouterVar string // name of the router variable (e.g., "appRouter")
}
ParseResult holds the result of parsing Go source for tRPC procedures.
func ParseDir ¶
func ParseDir(dir string) (*ParseResult, error)
ParseDir parses Go source files using the simpler go/parser approach (no type checking). This is a fallback when golang.org/x/tools/go/packages is not available. It recursively scans subdirectories.
func ParsePackage ¶
func ParsePackage(pattern string, routerVar string) (*ParseResult, error)
ParsePackage parses Go source files in the given directory pattern and extracts tRPC procedure registrations.
type ProcedureInfo ¶
type ProcedureInfo struct {
Name string
Type string // "query" or "mutation"
InputType types.Type
OutputType types.Type
RouterVar string // variable name of the router this is registered on
// AST-only fields (used when type checking is unavailable)
InputTypeName string // Go type expression as string (e.g., "ListTasksInput")
OutputTypeName string // Go type expression as string (e.g., "Task")
}
ProcedureInfo holds information about a discovered tRPC procedure.
type SchemaInfo ¶
type SchemaInfo struct {
Name string `json:"name"`
Type string `json:"type"` // "query" or "mutation"
}
SchemaInfo describes a procedure for the introspection endpoint.
type SchemaResponse ¶
type SchemaResponse struct {
Procedures []SchemaInfo `json:"procedures"`
}
SchemaResponse is the response for GET /trpc/__schema.
type StructDef ¶
type StructDef struct {
Name string
Fields []StructField
}
StructDef holds information about a struct type extracted from AST.
type StructField ¶
type StructField struct {
Name string
TypeExpr string // Go type expression as string (e.g., "string", "[]Task")
JSONName string
Optional bool // from omitempty tag
}
StructField holds information about a struct field extracted from AST.
type TSType ¶
type TSType struct {
Name string
Definition string
Inline string // for inline usage when no named type exists
}
TSType represents a generated TypeScript type.
type TypeMapper ¶
type TypeMapper struct {
// contains filtered or unexported fields
}
TypeMapper converts Go types to TypeScript type representations.
func (*TypeMapper) MapType ¶
func (m *TypeMapper) MapType(t types.Type) string
MapType maps a Go type to its TypeScript representation. Returns the TypeScript type string to use in references.
func (*TypeMapper) NamedTypes ¶
func (m *TypeMapper) NamedTypes() map[string]*TSType
NamedTypes returns all collected named type definitions, keyed by their TypeScript name.
func (*TypeMapper) RegisterEnums ¶
func (m *TypeMapper) RegisterEnums(enums []EnumInfo)
RegisterEnums registers detected enum patterns so the mapper can generate union types.