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 ¶
- func Declare[T any](name string, opts ...Option) *ast.SourceFile
- func Enum[T comparable](b *Binder, values ...T) ast.Type
- func Of[T any](b *Binder) ast.Type
- func TypeOf[T any](opts ...Option) (ast.Type, []ast.Decl)
- type ArrayPolicy
- type Binder
- func (b *Binder) Bind(rt reflect.Type) ast.Type
- func (b *Binder) Declarations() []ast.Decl
- func (b *Binder) Declare[T any]() *Binder
- func (b *Binder) Diagnostics() []Diagnostic
- func (b *Binder) Enum[T comparable](values ...T) ast.Type
- func (b *Binder) File(name string) *ast.SourceFile
- func (b *Binder) HasErrors() bool
- func (b *Binder) Lookup(rt reflect.Type) (string, bool)
- func (b *Binder) Map[T any](t ast.Type) *Binder
- func (b *Binder) MapFunc[T any](fn func(*Context) ast.Type) *Binder
- func (b *Binder) Of[T any]() ast.Type
- func (b *Binder) Options() *Options
- func (b *Binder) Ref[T any]() (ast.Type, bool)
- func (b *Binder) SortedDeclarations() []ast.Decl
- type Context
- type DefaultNamer
- type Diagnostic
- type EmbedPolicy
- type FieldRule
- type FieldRuleFunc
- type FieldSpec
- type Mapper
- type MapperFunc
- type Namer
- type NamerFunc
- type NullPolicy
- type Option
- func WithAny(t ast.Type) Option
- func WithArrays(p ArrayPolicy) Option
- func WithEmbeds(p EmbedPolicy) Option
- func WithExport(b bool) Option
- func WithFieldRule(r ...FieldRule) Option
- func WithInline(b bool) Option
- func WithInt64(t ast.Type) Option
- func WithMapper(m ...Mapper) Option
- func WithNamer(n Namer) Option
- func WithNulls(p NullPolicy) Option
- func WithReadonly(b bool) Option
- func WithTagKey(k string) Option
- func WithTime(t ast.Type) Option
- func WithTypeAliases() Option
- type Options
- type PrefixNamer
- type Severity
- type VerbatimNamer
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 ¶
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.
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 (*Binder) Declarations ¶
Declarations returns the declarations implied by everything bound so far, in discovery order. The order is deterministic across runs.
func (*Binder) Declare ¶
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) Map ¶
Map registers a mapper claiming exactly the Go type T.
b.Map[time.Time](ast.Ref("Date"))
func (*Binder) Ref ¶
Ref returns a reference to T's TypeScript name without projecting it, reporting false if T has not been bound.
func (*Binder) SortedDeclarations ¶
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.
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.
type Diagnostic ¶
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 ¶
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 ¶
MapExact returns a Mapper claiming exactly the Go type T.
bind.MapExact[uuid.UUID](ast.String)
type MapperFunc ¶
MapperFunc adapts a function to Mapper.
type Namer ¶
Namer assigns a TypeScript name to a named Go type. The binder still resolves collisions between distinct types that choose the same name.
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 WithArrays ¶
func WithArrays(p ArrayPolicy) Option
WithArrays sets the fixed-size array policy.
func WithExport ¶
WithExport controls whether declarations are exported.
func WithFieldRule ¶
WithFieldRule prepends struct field rules.
func WithInline ¶
WithInline emits anonymous object types rather than named interfaces.
func WithMapper ¶
WithMapper prepends type mappers, which are consulted before the built-ins.
func WithReadonly ¶
WithReadonly marks generated properties readonly.
func WithTagKey ¶
WithTagKey sets the struct tag used for field naming.
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 VerbatimNamer ¶
type VerbatimNamer struct{}
VerbatimNamer uses the Go type name unchanged apart from the sanitization needed to make it a legal identifier.