bind

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 21, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package bind projects Go types into TypeScript types.

The entry point is a type parameter, not a value:

b := bind.New()
t := bind.Of[User](b)        // a reference to "User"
file := b.File("models.ts")  // the declarations it implied

Defaults describe what encoding/json emits rather than what the Go declaration looks like: a *T field without omitempty becomes T | null, []byte becomes string, time.Time becomes string.

Every decision is overridable. Mapper intercepts type projection, FieldRule struct fields, and Namer type naming; user rules are consulted before the built-ins and the first to claim a type wins.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Declare

func Declare[T any](name string, opts ...Option) *ast.SourceFile

Declare projects T and returns a source file containing the declarations it implied.

func Enum

func Enum[T comparable](b *Binder, values ...T) ast.Type

Enum registers a named union alias for T over the supplied values, since reflection cannot enumerate Go constants.

bind.Enum(b, Active, Banned)  // type Status = 'active' | 'banned'

func Of

func Of[T any](b *Binder) ast.Type

Of projects the Go type argument into a TypeScript type.

Named struct types are registered as declarations and referenced by name, so the result is usually an *ast.TypeRef; collect the declarations with Binder.Declarations.

On Go 1.27 the equivalent method b.Of[T]() is also available.

func TypeOf

func TypeOf[T any](opts ...Option) (ast.Type, []ast.Decl)

TypeOf projects T with a throwaway binder, returning the type and the declarations it implied. Use a Binder when binding several related types.

Types

type ArrayPolicy

type ArrayPolicy uint8

ArrayPolicy decides how a fixed-size Go array becomes a TypeScript type.

const (
	// ArrayAsSlice renders [N]T as T[].
	ArrayAsSlice ArrayPolicy = iota
	// ArrayAsTuple renders [N]T as a tuple of N elements, preserving length.
	ArrayAsTuple
)

type Binder

type Binder struct {
	// contains filtered or unexported fields
}

Binder converts Go types to TypeScript and accumulates the declarations those conversions imply.

A Binder is stateful and not safe for concurrent use.

func New

func New(opts ...Option) *Binder

New returns a Binder configured from the supplied options.

func (*Binder) Bind

func (b *Binder) Bind(rt reflect.Type) ast.Type

Bind projects a reflect.Type. Prefer Of when the type is known statically.

func (*Binder) Declarations

func (b *Binder) Declarations() []ast.Decl

Declarations returns the declarations implied by everything bound so far, in discovery order. The order is deterministic across runs.

func (*Binder) Declare

func (b *Binder) Declare[T any]() *Binder

Declare projects T for its declarations alone, returning the binder so several types can be registered in one chain.

func (*Binder) Diagnostics

func (b *Binder) Diagnostics() []Diagnostic

Diagnostics returns the projections that could not be performed faithfully.

func (*Binder) Enum

func (b *Binder) Enum[T comparable](values ...T) ast.Type

Enum registers a named union alias for T over the supplied values.

func (*Binder) File

func (b *Binder) File(name string) *ast.SourceFile

File wraps the accumulated declarations in a source file.

func (*Binder) HasErrors

func (b *Binder) HasErrors() bool

HasErrors reports whether any diagnostic has error severity.

func (*Binder) Lookup

func (b *Binder) Lookup(rt reflect.Type) (string, bool)

Lookup returns the TypeScript name assigned to a Go type, if it has one.

func (*Binder) Map

func (b *Binder) Map[T any](t ast.Type) *Binder

Map registers a mapper claiming exactly the Go type T.

b.Map[time.Time](ast.Ref("Date"))

func (*Binder) MapFunc

func (b *Binder) MapFunc[T any](fn func(*Context) ast.Type) *Binder

MapFunc registers a mapper for T whose result is computed per projection.

func (*Binder) Of

func (b *Binder) Of[T any]() ast.Type

Of projects the Go type argument into a TypeScript type.

func (*Binder) Options

func (b *Binder) Options() *Options

Options returns a pointer to the binder's configuration.

func (*Binder) Ref

func (b *Binder) Ref[T any]() (ast.Type, bool)

Ref returns a reference to T's TypeScript name without projecting it, reporting false if T has not been bound.

func (*Binder) SortedDeclarations

func (b *Binder) SortedDeclarations() []ast.Decl

SortedDeclarations returns the declarations sorted by name.

type Context

type Context struct {
	// contains filtered or unexported fields
}

Context is the per-projection state handed to Mapper and FieldRule implementations. Use Context.Bind to recurse into component types.

func (*Context) Bind

func (c *Context) Bind(rt reflect.Type) ast.Type

Bind projects rt, consulting user mappers first and then the built-in rules.

func (*Context) Binder

func (c *Context) Binder() *Binder

Binder returns the owning binder.

func (*Context) Options

func (c *Context) Options() *Options

Options returns the binder's configuration.

func (*Context) Reportf

func (c *Context) Reportf(sev Severity, rt reflect.Type, format string, args ...any)

Reportf records a diagnostic.

type DefaultNamer

type DefaultNamer struct{}

DefaultNamer uses the Go type name, sanitized and capitalized.

Instantiated generics such as Box[int] become BoxInt: reflection reports only the instantiated type.

func (DefaultNamer) NameOf

func (DefaultNamer) NameOf(t reflect.Type) string

type Diagnostic

type Diagnostic struct {
	Severity Severity
	GoType   string
	Message  string
}

Diagnostic reports a projection that could not be performed faithfully.

Diagnostics are not fatal; a generator can use Binder.HasErrors to fail a build rather than emit a wrong type.

func (Diagnostic) String

func (d Diagnostic) String() string

type EmbedPolicy

type EmbedPolicy uint8

EmbedPolicy decides how an embedded Go struct becomes TypeScript.

const (
	// EmbedFlatten inlines the embedded struct's fields, as encoding/json does.
	EmbedFlatten EmbedPolicy = iota
	// EmbedExtends emits an extends clause referencing the embedded type.
	EmbedExtends
)

type FieldRule

type FieldRule interface {
	MapField(c *Context, f reflect.StructField) (FieldSpec, bool)
}

FieldRule projects a Go struct field. Returning false declines the field, passing it to the next rule and then to the built-in JSON rule.

type FieldRuleFunc

type FieldRuleFunc func(*Context, reflect.StructField) (FieldSpec, bool)

FieldRuleFunc adapts a function to FieldRule.

func (FieldRuleFunc) MapField

func (fn FieldRuleFunc) MapField(c *Context, f reflect.StructField) (FieldSpec, bool)

type FieldSpec

type FieldSpec struct {
	// Name is the TypeScript property name.
	Name string
	// Skip omits the field entirely.
	Skip bool
	// Optional emits name?: T.
	Optional bool
	// Readonly emits readonly name: T.
	Readonly bool
	// Nullable adds | null to the projected type.
	Nullable bool
	// Type overrides the projected type. When nil the type is derived from
	// the Go field type.
	Type ast.Type
	// Docs attaches a JSDoc comment.
	Docs *ast.Doc
}

FieldSpec describes how one Go struct field is projected.

type Mapper

type Mapper interface {
	MapType(c *Context, t reflect.Type) (ast.Type, bool)
}

Mapper projects a Go type into a TypeScript type. Returning false declines the type, passing it to the next mapper and then to the built-in rules.

func MapExact

func MapExact[T any](ts ast.Type) Mapper

MapExact returns a Mapper claiming exactly the Go type T.

bind.MapExact[uuid.UUID](ast.String)

func MapKind

func MapKind(k reflect.Kind, ts ast.Type) Mapper

MapKind returns a Mapper claiming every type of the given reflect kind.

func MapNamed

func MapNamed(pkgPath, name string, ts ast.Type) Mapper

MapNamed returns a Mapper claiming types by package path and name, for third-party types that cannot be named at compile time.

type MapperFunc

type MapperFunc func(*Context, reflect.Type) (ast.Type, bool)

MapperFunc adapts a function to Mapper.

func (MapperFunc) MapType

func (f MapperFunc) MapType(c *Context, t reflect.Type) (ast.Type, bool)

type Namer

type Namer interface {
	NameOf(reflect.Type) string
}

Namer assigns a TypeScript name to a named Go type. The binder still resolves collisions between distinct types that choose the same name.

type NamerFunc

type NamerFunc func(reflect.Type) string

NamerFunc adapts a function to Namer.

func (NamerFunc) NameOf

func (f NamerFunc) NameOf(t reflect.Type) string

type NullPolicy

type NullPolicy uint8

NullPolicy decides how a Go pointer becomes a TypeScript type.

const (
	// NullFromJSON follows encoding/json: an omittable pointer field becomes an
	// optional property, one that may marshal to null becomes T | null.
	NullFromJSON NullPolicy = iota
	// NullAsNull renders every pointer as T | null.
	NullAsNull
	// NullAsUndefined renders every pointer as T | undefined.
	NullAsUndefined
	// NullAsOptional renders every pointer field as an optional property.
	NullAsOptional
	// NullAsBoth renders every pointer as T | null | undefined.
	NullAsBoth
	// NullIgnore erases pointers entirely, rendering *T as T.
	NullIgnore
)

type Option

type Option func(*Options)

Option mutates Options.

func WithAny

func WithAny(t ast.Type) Option

WithAny sets the type produced for interface{}.

func WithArrays

func WithArrays(p ArrayPolicy) Option

WithArrays sets the fixed-size array policy.

func WithEmbeds

func WithEmbeds(p EmbedPolicy) Option

WithEmbeds sets the embedded struct policy.

func WithExport

func WithExport(b bool) Option

WithExport controls whether declarations are exported.

func WithFieldRule

func WithFieldRule(r ...FieldRule) Option

WithFieldRule prepends struct field rules.

func WithInline

func WithInline(b bool) Option

WithInline emits anonymous object types rather than named interfaces.

func WithInt64

func WithInt64(t ast.Type) Option

WithInt64 sets the type produced for 64-bit integers.

func WithMapper

func WithMapper(m ...Mapper) Option

WithMapper prepends type mappers, which are consulted before the built-ins.

func WithNamer

func WithNamer(n Namer) Option

WithNamer sets the type namer.

func WithNulls

func WithNulls(p NullPolicy) Option

WithNulls sets the pointer projection policy.

func WithReadonly

func WithReadonly(b bool) Option

WithReadonly marks generated properties readonly.

func WithTagKey

func WithTagKey(k string) Option

WithTagKey sets the struct tag used for field naming.

func WithTime

func WithTime(t ast.Type) Option

WithTime sets the type produced for time.Time.

func WithTypeAliases

func WithTypeAliases() Option

WithTypeAliases emits type aliases instead of interface declarations.

type Options

type Options struct {
	// Mappers are consulted before the built-in type rules, in order.
	Mappers []Mapper

	// FieldRules are consulted before the built-in struct field rule, in order.
	FieldRules []FieldRule

	// Namer assigns TypeScript names to named Go types.
	Namer Namer

	// TagKey is the struct tag read for field naming. Defaults to "json".
	TagKey string

	// OverrideTag is the struct tag read for TypeScript-specific overrides.
	// Defaults to "ts".
	OverrideTag string

	// DocTag is the struct tag read for a field's JSDoc text.
	// Defaults to "tsdoc".
	DocTag string

	// Nulls decides how pointers are projected.
	Nulls NullPolicy

	// Arrays decides how fixed-size arrays are projected.
	Arrays ArrayPolicy

	// Embeds decides how embedded structs are projected.
	Embeds EmbedPolicy

	// Any is the type produced for interface{} and non-empty interfaces.
	// Defaults to unknown, which forces consumers to narrow before use.
	Any ast.Type

	// Bytes is the type produced for []byte. Defaults to string, matching
	// encoding/json's base64 encoding.
	Bytes ast.Type

	// Time is the type produced for time.Time. Defaults to string.
	Time ast.Type

	// Duration is the type produced for time.Duration. Defaults to number,
	// matching encoding/json's nanosecond integer.
	Duration ast.Type

	// Int64 is the type produced for int64 and uint64. Defaults to number.
	// Set to ast.String when the wire format uses ,string, or to a union
	// when precision beyond 2^53 matters.
	Int64 ast.Type

	// Readonly marks every generated property readonly.
	Readonly bool

	// Export marks every generated declaration exported. Defaults to true.
	Export bool

	// Inline emits anonymous object types instead of named interfaces for
	// named Go structs. Recursive types are rejected in this mode, since an
	// inline type cannot refer to itself.
	Inline bool

	// Interfaces emits struct types as interface declarations. When false,
	// type aliases are emitted instead, which composes better with mapped and
	// conditional types at the cost of slower checking on large graphs.
	Interfaces bool

	// SkipUnexported skips unexported struct fields. Defaults to true;
	// unexported fields are invisible to encoding/json.
	SkipUnexported bool
}

Options configures a Binder. Construct one via New with Option values so that unset fields take their defaults.

type PrefixNamer

type PrefixNamer struct{ Prefix string }

PrefixNamer prefixes the type name.

func (PrefixNamer) NameOf

func (p PrefixNamer) NameOf(t reflect.Type) string

type Severity

type Severity uint8

Severity classifies a Diagnostic.

const (
	SeverityWarning Severity = iota
	SeverityError
)

func (Severity) String

func (s Severity) String() string

type VerbatimNamer

type VerbatimNamer struct{}

VerbatimNamer uses the Go type name unchanged apart from the sanitization needed to make it a legal identifier.

func (VerbatimNamer) NameOf

func (VerbatimNamer) NameOf(t reflect.Type) string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL