### Install Tygo CLI and Library Source: https://context7.com/gzuidhof/tygo/llms.txt Install the Tygo command-line interface globally using `go install` or add it as a dependency to your Go project using `go get`. ```shell # Install the CLI globally go install github.com/gzuidhof/tygo@latest # Or use as a Go library go get github.com/gzuidhof/tygo ``` -------------------------------- ### Install Tygo CLI Source: https://github.com/gzuidhof/tygo/blob/main/README.md Install the Tygo command-line tool using go install. ```shell go install github.com/gzuidhof/tygo@latest ``` -------------------------------- ### Empty File Example: Go Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/simple.md An example of an empty Go file, which should result in an empty TypeScript file. ```go ``` -------------------------------- ### Configure Tygo Package Generation Source: https://github.com/gzuidhof/tygo/blob/main/README.md Example configuration for Tygo, specifying package path, output location, indentation, type mappings, and excluded files. ```yaml packages: - path: "github.com/my/package" output_path: "webapp/api/types.ts" indent: " " type_mappings: time.Time: "string" my.Type: "SomeType" frontmatter: | "import {SomeType} from "../lib/sometype.ts" exclude_files: - "private_stuff.go" extends: "SomeType" enum_style: "enum" ``` -------------------------------- ### Tygo CLI Configuration Source: https://github.com/gzuidhof/tygo/blob/main/README.md Example `tygo.yaml` configuration file specifying packages to convert and custom type mappings for Go types to TypeScript. ```yaml packages: - path: "github.com/gzuidhof/tygo/examples/bookstore" type_mappings: time.Time: "string /* RFC3339 */" null.String: "null | string" null.Bool: "null | boolean" uuid.UUID: "string /* uuid */" uuid.NullUUID: "null | string /* uuid */" ``` -------------------------------- ### Go Struct to TypeScript Interface Generation Source: https://context7.com/gzuidhof/tygo/llms.txt Example of a Go input struct with various types and its corresponding TypeScript interface output, demonstrating type mapping. ```go // Go input type Event struct { ID uuid.UUID `json:"id"` Name null.String `json:"name"` CreatedAt time.Time `json:"created_at"` Duration time.Duration `json:"duration"` } ``` ```typescript // TypeScript output export interface Event { id: string /* uuid */; name: string | null; created_at: string /* RFC3339 */; duration: number /* int, ns */; } ``` -------------------------------- ### Tygo Global Type Mappings Source: https://github.com/gzuidhof/tygo/blob/main/README.md Example YAML snippet showing how to specify default type mappings that apply globally across all packages converted by Tygo. ```yaml # You can specify default mappings that will apply to all packages. type_mappings: time.Time: "string /* RFC3339 */" ``` -------------------------------- ### Golang Input for Tygo Source: https://github.com/gzuidhof/tygo/blob/main/README.md Example of Go source code with various types, including maps, slices, pointers, and embedded structs, demonstrating features like comment preservation and custom type tags. ```go // Comments are kept :) type ComplexType map[string]map[uint16]*uint32 type UserRole = string const ( UserRoleDefault UserRole = "viewer" UserRoleEditor UserRole = "editor" // Line comments are also kept ) type UserEntry struct { // Instead of specifying `tstype` we could also declare the typing // for uuid.NullUUID in the config file. ID uuid.NullUUID `json:"id" tstype:"string | null"` Preferences map[string]struct { Foo uint32 `json:"foo"` // An unknown type without a `tstype` tag or mapping in the config file // becomes `any` Bar uuid.UUID `json:"bar"` } `json:"prefs"` MaybeFieldWithStar *string `json:"address"` Nickname string `json:"nickname,omitempty"` Role UserRole `json:"role"` CreatedAt time.Time `json:"created_at,omitzero" Complex ComplexType `json:"complex"` unexported bool // Unexported fields are omitted Ignored bool `tstype:"-"` // Fields with - are omitted too } type ListUsersResponse struct { Users []UserEntry `json:"users"` } ``` -------------------------------- ### Define Union Types and Interfaces in Go Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/generic.md Demonstrates Go syntax for defining union types using interfaces and specifying derived types. Includes examples of empty interfaces and type aliases. ```go type UnionType interface { // Comment for fields are possible uint64 | string | *bool // comment after // Comment for a method SomeMethod() string } type Derived interface { ~int | string // Line comment } type Any interface { string | any } type Empty interface{} type Something any type EmptyStruct struct{} ``` -------------------------------- ### Go Struct with YAML Tags Source: https://github.com/gzuidhof/tygo/blob/main/README.md Example of a Go struct demonstrating how `yaml` tags are used to map struct fields to YAML keys. Untagged fields are handled based on the configured flavor. ```go // Golang input type Foo struct { TaggedField string `yaml:"custom_field_name_in_yaml"` UntaggedField string } ``` -------------------------------- ### Tygo Library Mode Usage Source: https://github.com/gzuidhof/tygo/blob/main/README.md Example of using Tygo as a library in Go code to generate TypeScript typings programmatically. ```go config := &tygo.Config{ Packages: []*tygo.PackageConfig{ &tygo.PackageConfig{ Path: "github.com/gzuidhof/tygo/examples/bookstore", }, }, } gen := tygo.New(config) err := gen.Generate() ``` -------------------------------- ### Generic Types in Tygo Source: https://github.com/gzuidhof/tygo/blob/main/README.md Shows how Tygo supports Go generics (version >= 1.18) for creating flexible types. This example defines a union type and a generic struct that uses these types. ```go type UnionType interface { uint64 | string } type ABCD[A, B string, C UnionType, D int64 | bool] struct { A A `json:"a"` B B `json:"b"` C C `json:"c"` D D `json:"d"` } ``` ```typescript export type UnionType = number /* uint64 */ | string; export interface ABCD< A extends string, B extends string, C extends UnionType, D extends number /* int64 */ | boolean > { a: A; b: B; c: C; d: D; } ``` -------------------------------- ### Numeric Enum Generation with Iota (enum_style: "enum") Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/enum.md Generates numeric enums using Go's iota. TypeScript enums will be assigned sequential numeric values starting from 0. ```yaml enum_style: "enum" ``` ```go type Priority int const ( PriorityLow Priority = iota PriorityMedium PriorityHigh ) ``` ```typescript export enum Priority { Low = 0, Medium, High, } ``` -------------------------------- ### Go Directives and Constants Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/directive.md Illustrates Go directives and constant declarations with various comment styles. ```go // Comment above a directive // //go:foo //go:bar const SomeValue = 3 //comment:test // Empty Comment const AnotherValue = 4 // //go:something const DirectiveOnly = 5 // RepoIndexerType specifies the repository indexer type type RepoIndexerType int //revive:disable-line:exported const ( // RepoIndexerTypeCode code indexer RepoIndexerTypeCode RepoIndexerType = iota // 0 // RepoIndexerTypeStats repository stats indexer RepoIndexerTypeStats // 1 ) const A = "a" const B = "a" const C = "c" ``` -------------------------------- ### Configure Tygo Generation with YAML Source: https://context7.com/gzuidhof/tygo/llms.txt The `tygo.yaml` file defines package processing, type mappings, output paths, and other generation options. Global mappings can be overridden per package. ```yaml # Global type mappings applied to every package type_mappings: time.Duration: "number /* int, ns */" packages: - path: "github.com/my/api" # Custom output path; if a directory is given, writes index.ts inside it output_path: "webapp/src/types/api.ts" # Indentation string (default: two spaces; use \t for tabs) indent: " " # Per-package type mappings (override global) type_mappings: time.Time: "string /* RFC3339 */" null.String: "string | null" null.Bool: "boolean | null" uuid.UUID: "string /* uuid */" uuid.NullUUID: "string | null /* uuid */" # Raw TypeScript inserted at the top of the output file frontmatter: | import { SomeType } from "../lib/sometype"; # Go source files to exclude from conversion exclude_files: - "internal_only.go" # If set, only these files are included (overrides exclude_files) include_files: - "public_api.go" # Type used for unrecognized Go types: "any" (default) or "unknown" fallback_type: "unknown" # Key naming: "default" (respects json/yaml tags) or "yaml" (lowercases untagged fields) flavor: "default" # Comment preservation: "default" (all), "types" (type-level only), "none" preserve_comments: "default" # All generated interfaces extend this TypeScript type extends: "BaseModel" # Optional field marker: "undefined" (default) or "null" optional_type: "undefined" # Constant/enum generation: "const" (default), "enum", or "union" enum_style: "const" ``` -------------------------------- ### Basic Type Mappings: TypeScript Equivalents Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/simple.md Provides the TypeScript representation for the Go types defined previously. This highlights how Go's primitive types are translated, with comments indicating the original Go type. ```typescript export type MyUint8 = number /* uint8 */; export type MyInt = number /* int */; export type MyString = string; export type MyAny = any; /** * Should be a number in TypeScript. */ export type MyRune = number /* rune */; ``` -------------------------------- ### Basic Type Mappings: Go to TypeScript Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/simple.md Shows the direct mapping of fundamental Go types to their TypeScript equivalents. Note how numeric types like uint8 and rune are mapped to 'number' in TypeScript, with original Go types noted in comments. ```go type MyUint8 uint8 type MyInt int type MyString string type MyAny any // Should be a number in TypeScript. type MyRune rune ``` -------------------------------- ### Configure Type Mappings in Tygo Source: https://context7.com/gzuidhof/tygo/llms.txt Define global and per-package type mappings for common Go types to their TypeScript equivalents. Per-package mappings override global ones. ```yaml type_mappings: time.Duration: "number /* int, ns */" # global packages: - path: "github.com/my/api" type_mappings: time.Time: "string /* RFC3339 */" # per-package (overrides global if duplicated) null.String: "string | null" null.Bool: "boolean | null" uuid.UUID: "string /* uuid */" uuid.NullUUID: "string | null /* uuid */" my.CustomType: "MyTSType" ``` -------------------------------- ### Define Generic Structs with Value and Pointer Fields in Go Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/generic.md Illustrates Go syntax for creating generic structs that can hold values and pointers, with type constraints. ```go type ValAndPtr[V any, PT *V, Unused ~uint64] struct { Val V // Comment for ptr field Ptr PT // ptr line comment } type ABCD[A, B string, C UnionType, D int64 | bool] struct { A A `json:"a"` B B `json:"b"` C C `json:"c"` D D `json:"d"` } type Foo[A string | uint64, B *A] struct { Bar A Boo B } type WithFooGenericTypeArg[A Foo[string, *string]] struct { SomeField A `json:"some_field"` } ``` -------------------------------- ### File Filtering with `exclude_files` and `include_files` Source: https://context7.com/gzuidhof/tygo/llms.txt Use `exclude_files` to omit specific Go source files from transpilation, or `include_files` to specify only which files should be processed. These options are mutually exclusive. ```yaml # tygo.yaml packages: - path: "github.com/my/api" # Exclude specific files exclude_files: - "internal_handlers.go" - "test_helpers.go" - path: "github.com/my/api/models" # Allow only these files (mutually exclusive with exclude_files) include_files: - "user.go" - "product.go" ``` -------------------------------- ### Struct Inheritance in Tygo Source: https://github.com/gzuidhof/tygo/blob/main/README.md Demonstrates how to extend structs in Tygo using the `tstype:",extends"` tag. Use `Partial` for optional pointer extensions and `tstype:",extends,required"` to mark them as required. ```go import "example.com/external" type Base struct { Name string `json:"name"` } type Base2[T string | int] struct { ID T `json:"id"` } type OptionalPtr struct { Field string `json:"field"` } type Other[T int] struct { *Base ` tstype:",extends,required"` Base2[T] ` tstype:",extends" *OptionalPtr ` tstype:",extends" external.AnotherStruct ` tstype:",extends" OtherValue string ` json:"other_value" } ``` ```typescript export interface Base { name: string; } export interface Base2 { id: T; } export interface OptionalPtr { field: string; } export interface Other extends Base, Base2, Partial, external.AnotherStruct { other_value: string; } ``` -------------------------------- ### Configure Tygo for YAML Flavor Source: https://github.com/gzuidhof/tygo/blob/main/README.md Use this configuration to enable YAML-specific field name transformations, such as downcasing untagged fields to match `gopkg.in/yaml.v2` behavior. ```yaml packages: - path: "github.com/my/package" output_path: "webapp/api/types.ts" flavor: "yaml" ``` -------------------------------- ### Define Struct with Any Field Type in Go Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/generic.md Demonstrates a Go generic struct where one field can be of any type, alongside a fixed string field. ```go type AnyStructField[T any] struct { Value T SomeField string } ``` -------------------------------- ### Constants with Comma Separation: Go Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/simple.md Defines multiple Go constants on a single line, separated by commas, with an associated inline comment. ```go const Pi, E = 3.14, 2.71 // A comment on constants separated by a comma ``` -------------------------------- ### Unexported Elements: Go Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/simple.md Demonstrates unexported constants, types, and fields in Go, along with comments associated with them. Also shows a mix of unexported and exported constants. ```go // A comment on an unexported constant const myValue = 3 // A comment on an unexported type type myType struct { // A comment on an unexported field field string } // Mixed unexported and exported const ( unexportedValue = 7 // A comment on an unexported constant ExportedValue = 42 // A comment on an exported constant ) // Unexported group const ( unexportedValue1 = 1 // A comment on an unexported constant unexportedValue2 = 2 // Another comment on an unexported constant ) ``` -------------------------------- ### Emit Multi-line TypeScript with `//tygo:emit` on String Var Source: https://github.com/gzuidhof/tygo/blob/main/README.md Emitting multi-line TypeScript code, such as tuple definitions, by using `//tygo:emit` on a Go string variable. ```golang //tygo:emit var _ = `export type StructAsTuple=[ a:number, b:number, c:string, ] ` type CustomMarshalled struct { Content []StructAsTuple `json:"content"` } ``` -------------------------------- ### TypeScript Equivalents for Go Directives and Constants Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/directive.md Shows TypeScript code that mirrors the structure and intent of the Go directives and constants. ```typescript /** * Comment above a directive */ export const SomeValue = 3; /** * Empty Comment */ export const AnotherValue = 4; export const DirectiveOnly = 5; /** * RepoIndexerType specifies the repository indexer type */ export type RepoIndexerType = number /* int */; /** * RepoIndexerTypeCode code indexer */ export const RepoIndexerTypeCode: RepoIndexerType = 0; // 0 /** * RepoIndexerTypeStats repository stats indexer */ export const RepoIndexerTypeStats: RepoIndexerType = 1; // 1 export const A = "a"; export const B = "a"; export const C = "c"; ``` -------------------------------- ### Mixed Const Blocks Generation Source: https://github.com/gzuidhof/tygo/blob/main/README.md Demonstrates Tygo's behavior with mixed Go constant blocks, generating enums for enum-like constants and individual const declarations for others. ```go type UserRole = string const ( UserRoleAdmin UserRole = "admin" UserRoleGuest UserRole = "guest" MaxRetries = 5 DefaultTimeout = 30 ) ``` ```typescript export enum UserRole { Admin = "admin", Guest = "guest", } export const MaxRetries = 5; export const DefaultTimeout = 30; ``` ```typescript export const UserRoleAdmin = "admin"; export const UserRoleGuest = "guest"; export type UserRole = typeof UserRoleAdmin | typeof UserRoleGuest; export const MaxRetries = 5; export const DefaultTimeout = 30; ``` -------------------------------- ### Define Single Generic Type in Go Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/generic.md Shows how to define a simple generic type in Go with a single type parameter and a specific type alias. ```go type Single[S string | uint] struct { Field S } type SingleSpecific = Single[string] ``` -------------------------------- ### Struct Translation with Comments: Go Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/simple.md Defines a Go struct including various comment styles: before the struct, before a field, and inline after a field. It also demonstrates the use of 'any' for fields and fields with imported types. ```go // Comment for a struct type MyStruct struct { SomeField any `json:"some_field"` // Comment for a field OtherField bool // Comment after line FieldWithImportedType some.Type } ``` -------------------------------- ### Basic Enum Generation (enum_style: "enum") Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/enum.md Generates string enums using the 'enum' style. This is useful for defining a fixed set of string values for a type. ```yaml enum_style: "enum" ``` ```go type UserRole = string const ( UserRoleDefault UserRole = "viewer" UserRoleEditor UserRole = "editor" ) ``` ```typescript export enum UserRole { Default = "viewer", Editor = "editor", } ``` -------------------------------- ### No Enum Style Configured (Defaults to "const") Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/enum.md If no enum_style is configured, Tygo defaults to the 'const' behavior, generating string constants for each Go constant. ```go type UserRole = string const ( UserRoleDefault UserRole = "viewer" UserRoleEditor UserRole = "editor" ) ``` ```typescript export type UserRole = string; export const UserRoleDefault: UserRole = "viewer"; export const UserRoleEditor: UserRole = "editor"; ``` -------------------------------- ### Go Structs with Inheritance and Generics Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/inheritance.md Defines Go structs that utilize embedding for inheritance and generics with type constraints. These structs serve as a basis for demonstrating Tygo's translation capabilities. ```go type Base struct { Name string `json:"name"` } type Base2[T string | int] struct { ID T `json:"id"` } type Base3[T string, X int] struct { Class T `json:"class"` Level X `json:"level"` } type Other[T int, X string] struct { *Base `tstype:",extends,required"` Base2[T] `tststype:",extends"` *Base3[X, T] `tstype:",extends"` OtherWithBase Base ` json:"otherWithBase"` OtherWithBase2 Base2[X] ` json:"otherWithBase2"` OtherValue string ` json:"otherValue"` Author bookapp.AuthorWithInheritance[T] `tstype:"bookapp.AuthorWithInheritance" json:"author"` bookapp.Book `tstype:",extends"` TextBook *bookapp.TextBook[T] `tstype:",extends,required"` } ``` -------------------------------- ### Generate TypeScript Types with Tygo CLI Source: https://context7.com/gzuidhof/tygo/llms.txt Use the `tygo generate` command to create TypeScript definitions. It can use a default `tygo.yaml` config or a custom path. Other flags control version display and debug output. ```shell # Generate with default config file (tygo.yaml) tygo generate # Use a custom config file path tygo generate --config ./config/tygo.yaml # Show version tygo --version # Enable debug output tygo generate -D ``` -------------------------------- ### Handle Go Interfaces in Tygo Source: https://context7.com/gzuidhof/tygo/llms.txt Plain Go interfaces with methods are converted to `any`, while union constraint interfaces are converted to TypeScript union types. ```go // Go input // Plain interface with methods → any type Repository interface { FindByID(id string) error } // Union constraint interface → union type type NumberOrString interface { uint64 | string } ``` ```typescript // TypeScript output export type Repository = any; export type NumberOrString = number /* uint64 */ | string; ``` -------------------------------- ### Define Generic Slice Type in Go Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/generic.md Illustrates how to define a generic type in Go that represents a slice of a specific type. ```go type JsonArray[T any] []T ``` -------------------------------- ### Define Union Types and Interfaces in TypeScript Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/generic.md Shows the TypeScript equivalents for Go's union types and interfaces, including mapped types and type aliases. ```typescript export type UnionType = /** * Comment for fields are possible */ number /* uint64 */ | string | boolean | undefined // comment after ; export type Derived = number /* int */ | string // Line comment ; export type Any = string | unknown; export type Empty = unknown; export type Something = any; export interface EmptyStruct { } ``` -------------------------------- ### String Enums Generation Source: https://github.com/gzuidhof/tygo/blob/main/README.md Illustrates how Tygo generates TypeScript enums or union types from Go string constants. Requires constants to have a consistent prefix and type. ```go type Status = string const ( StatusActive Status = "active" StatusInactive Status = "inactive" StatusPending Status = "pending" ) ``` ```typescript export enum Status { Active = "active", Inactive = "inactive", Pending = "pending", } ``` ```typescript export const StatusActive = "active"; export const StatusInactive = "inactive"; export const StatusPending = "pending"; export type Status = typeof StatusActive | typeof StatusInactive | typeof StatusPending; ``` -------------------------------- ### TypeScript Interfaces for Inherited Go Structs Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/inheritance.md Translates the Go structs into TypeScript interfaces, preserving inheritance, generic types, and type constraints. This demonstrates how Tygo maps Go's composition and generics to TypeScript. ```typescript export interface Base { name: string; } export interface Base2 { id: T; } export interface Base3 { class: T; level: X; } export interface Other extends Base, Base2, Partial>, bookapp.Book, bookapp.TextBook { otherWithBase: Base; otherWithBase2: Base2; otherValue: string; author: bookapp.AuthorWithInheritance; } ``` -------------------------------- ### Type Definition with Inline Comment: Go Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/simple.md Defines a Go type with both a preceding comment and an inline comment. This demonstrates how comments are associated with type definitions. ```go // Foo type MyValue int // Bar ``` -------------------------------- ### Basic Union Enum Generation (enum_style: "union") Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/enum.md Generates string unions using the 'union' style. This creates individual constants for each value and a union type. ```yaml enum_style: "union" ``` ```go type UserRole = string const ( UserRoleDefault UserRole = "viewer" UserRoleEditor UserRole = "editor" ) ``` ```typescript export const UserRoleDefault = "viewer"; export const UserRoleEditor = "editor"; export type UserRole = typeof UserRoleDefault | typeof UserRoleEditor; ``` -------------------------------- ### Go `iota` and Constant Group Resolution Source: https://context7.com/gzuidhof/tygo/llms.txt Tygo resolves `iota` expressions at generation time, correctly handling skipped entries, resets, and arithmetic offsets for Go constants. ```go // Go input — abstract/iota.go type MyIotaType int const ( Zero MyIotaType = iota // 0 One // 1 Two // 2 _ // 3 (skipped) Four // 4 FourString string = "four" _ AlsoFourString // still "four" Five = 5 FiveAgain // 5 Sixteen = iota + 6 // 10 + 6 = 16 Seventeen // 11 + 6 = 17 ) ``` ```typescript // TypeScript output export type MyIotaType = number /* int */; export const Zero: MyIotaType = 0; export const One: MyIotaType = 1; export const Two: MyIotaType = 2; export const Four: MyIotaType = 4; export const FourString: string = "four"; export const AlsoFourString: string = "four"; export const Five = 5; export const FiveAgain = 5; export const Sixteen = 10 + 6; export const Seventeen = 11 + 6; ``` -------------------------------- ### Numeric Enums Generation with iota Source: https://github.com/gzuidhof/tygo/blob/main/README.md Shows Tygo's handling of Go numeric constants defined with `iota`. It generates TypeScript enums or union types based on the `enum_style` configuration. ```go type Priority int const ( PriorityLow Priority = iota PriorityMedium PriorityHigh ) ``` ```typescript export enum Priority { Low = 0, Medium, High, } ``` ```typescript export const PriorityLow = 0; export const PriorityMedium = 1; export const PriorityHigh = 2; export type Priority = typeof PriorityLow | typeof PriorityMedium | typeof PriorityHigh; ``` -------------------------------- ### Generate TypeScript Types Programmatically with Go Library Source: https://context7.com/gzuidhof/tygo/llms.txt Use the Tygo Go library to generate TypeScript types within your application. Configure mappings, packages, and other options via the `tygo.Config` struct. ```go package main import ( "log" "github.com/gzuidhof/tygo/tygo" ) func main() { config := &tygo.Config{ // Optional global type mappings TypeMappings: map[string]string{ "time.Duration": "number /* nanoseconds */", }, Packages: []*tygo.PackageConfig{ { Path: "github.com/my/api", OutputPath: "webapp/src/types.ts", TypeMappings: map[string]string{ "time.Time": "string /* RFC3339 */", "uuid.UUID": "string /* uuid */", "null.String": "string | null", }, Frontmatter: "import { UUID } from './uuid';\n", FallbackType: "unknown", EnumStyle: "enum", }, }, } gen := tygo.New(config) // Optionally override a type mapping after construction gen.SetTypeMapping("my.CustomType", "MyTSType") if err := gen.Generate(); err != nil { log.Fatalf("tygo generation failed: %v", err) } // Output written to webapp/src/types.ts } ``` -------------------------------- ### Generated TypeScript Output Source: https://github.com/gzuidhof/tygo/blob/main/README.md The corresponding TypeScript types generated from the Go input, showing how comments, type mappings, and Go types are translated. ```typescript /** * Comments are kept :) */ export type ComplexType = { [key: string]: { [key: number /* uint16 */]: number /* uint32 */ | undefined; }; }; export type UserRole = string; export const UserRoleDefault: UserRole = "viewer"; export const UserRoleEditor: UserRole = "editor"; // Line comments are also kept export interface UserEntry { /** * Instead of specifying `tstype` we could also declare the typing * for uuid.NullUUID in the config file. */ id: string | null; prefs: { [key: string]: { foo: number /* uint32 */; /** * An unknown type without a `tstype` tag or mapping in the config file * becomes `any` */ bar: any /* uuid.UUID */; }; }; address?: string; nickname?: string; role: UserRole; created_at?: string /* RFC3339 */; complex: ComplexType; } export interface ListUsersResponse { users: UserEntry[]; } ``` -------------------------------- ### Struct Fields with Comma Separation: Go Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/simple.md Illustrates Go struct definitions where multiple fields of the same type are declared on a single line, separated by commas. Comments are associated with these fields. ```go type A struct { Foo, Bar, baz string // A comment on fields separated by a comma } type B struct { // A comment above the fields separated by a comma Foo, Bar, baz string } ``` -------------------------------- ### Frontmatter for Header Injection Source: https://context7.com/gzuidhof/tygo/llms.txt The `frontmatter` option allows injecting raw TypeScript code at the beginning of the output file. This is useful for adding necessary imports for types referenced in `tstype` tags or `type_mappings`. ```yaml # tygo.yaml packages: - path: "github.com/my/api" type_mappings: bookapp.Book: "bookapp.Book" frontmatter: | import * as bookapp from "../bookstore"; import type { UUID } from '../uuid'; ``` ```typescript // Generated output header // Code generated by tygo. DO NOT EDIT. import * as bookapp from "../bookstore"; import type { UUID } from '../uuid'; ////////// // source: api.go // ... generated types follow ``` -------------------------------- ### Map Go Generic Types to TypeScript Source: https://context7.com/gzuidhof/tygo/llms.txt Tygo maps Go type parameters and constraints to TypeScript generic parameters with `extends` bounds. Union types in Go are mapped to union types in TypeScript. ```go type UnionType interface { uint64 | string | *bool } type ABCD[A, B string, C UnionType, D int64 | bool] struct { A A `json:"a"` B B `json:"b"` C C `json:"c"` D D `json:"d"` } type AnyStructField[T any] struct { Value T SomeField string } type JsonArray[T any] []T type SingleSpecific = Single[string] ``` ```typescript export type UnionType = number /* uint64 */ | string | boolean | undefined; export interface ABCD< A extends string, B extends string, C extends UnionType, D extends number /* int64 */ | boolean > { a: A; b: B; c: C; d: D; } export interface AnyStructField { Value: T; SomeField: string; } export type JsonArray = T[]; export type SingleSpecific = Single; ``` -------------------------------- ### Define Struct with Any Field Type in TypeScript Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/generic.md Shows the TypeScript interface for a Go generic struct with an 'any' type field. ```typescript export interface AnyStructField { Value: T; SomeField: string; } ``` -------------------------------- ### Configure Global Interface Inheritance in Tygo Source: https://context7.com/gzuidhof/tygo/llms.txt Use the `extends` configuration to make all generated interfaces inherit from a base TypeScript type, useful for ORM integration. ```yaml packages: - path: "github.com/my/api" extends: "BaseEntity" frontmatter: | export interface BaseEntity { _type: string; } ``` ```typescript // TypeScript output export interface BaseEntity { _type: string; } export interface User extends BaseEntity { id: string; name: string; } export interface Product extends BaseEntity { sku: string; price: number; } ``` -------------------------------- ### Emit TypeScript Types with `//tygo:emit` Directive Source: https://github.com/gzuidhof/tygo/blob/main/README.md Using the `//tygo:emit` directive in Go comments to directly emit TypeScript type definitions before a struct. ```golang //tygo:emit export type Genre = "novel" | "crime" | "fantasy" type Book struct { Title string `json:"title"` Genre string `json:"genre" tstype:"Genre"` } ``` -------------------------------- ### Numeric Union Enum with Iota (enum_style: "union") Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/enum.md Generates numeric union types using Go's iota. Each numeric constant is exported, and a union type is created from them. ```yaml enum_style: "union" ``` ```go type Priority int const ( PriorityLow Priority = iota PriorityMedium PriorityHigh ) ``` ```typescript export const PriorityLow = 0; export const PriorityMedium = 1; export const PriorityHigh = 2; export type Priority = typeof PriorityLow | typeof PriorityMedium | typeof PriorityHigh; ``` -------------------------------- ### Optional Field Handling: Null vs Undefined Source: https://context7.com/gzuidhof/tygo/llms.txt Configure how pointer fields are translated to TypeScript using `optional_type`. The default `"undefined"` results in `field?: Type`, while `"null"` produces `field: Type | null`, aligning with JSON marshaling that omits fields as `null`. ```yaml packages: - path: "github.com/my/api" optional_type: "null" ``` ```go // Go input type Response struct { Data string `json:"data"` Message *string `json:"message"` } ``` ```typescript // optional_type: "undefined" (default) export interface Response { data: string; message?: string; } // optional_type: "null" export interface Response { data: string; message: string | null; } ``` -------------------------------- ### Union Enum with Comments (enum_style: "union") Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/enum.md Generates union types with comments preserved from Go. Each constant and the union type are documented. ```yaml enum_style: "union" ``` ```go // User role enumeration type Status = string const ( // Default status for new users StatusActive Status = "active" StatusInactive Status = "inactive" // User is temporarily disabled ) ``` ```typescript /** * User role enumeration */ /** * Default status for new users */ export const StatusActive = "active"; export const StatusInactive = "inactive"; // User is temporarily disabled export type Status = typeof StatusActive | typeof StatusInactive; ``` -------------------------------- ### Go `enum_style` for TypeScript Enums and Unions Source: https://context7.com/gzuidhof/tygo/llms.txt When `enum_style` is set to `"enum"` or `"union"`, Tygo converts Go constant groups with common types and prefixes into TypeScript enums or union types. ```go // Go input type Status = string const ( StatusActive Status = "active" StatusInactive Status = "inactive" StatusPending Status = "pending" ) type Priority int const ( PriorityLow Priority = iota PriorityMedium PriorityHigh ) ``` ```typescript // enum_style: "enum" export enum Status { Active = "active", Inactive = "inactive", Pending = "pending", } export enum Priority { Low = 0, Medium, High, } // enum_style: "union" export const StatusActive = "active"; export const StatusInactive = "inactive"; export const StatusPending = "pending"; export type Status = typeof StatusActive | typeof StatusInactive | typeof StatusPending; export const PriorityLow = 0; export const PriorityMedium = 1; export const PriorityHigh = 2; export type Priority = typeof PriorityLow | typeof PriorityMedium | typeof PriorityHigh; ``` -------------------------------- ### Generated TypeScript Interface Source: https://github.com/gzuidhof/tygo/blob/main/README.md The TypeScript interface generated by Tygo from the Go struct, reflecting the `yaml` tags and the configured flavor for untagged fields. ```typescript // Typescript output export interface Foo { custom_field_name_in_yaml: string; untaggedfield: string; } ``` -------------------------------- ### Enum Generation with Comments (enum_style: "enum") Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/enum.md Includes comments from Go constants in the generated TypeScript enums. This helps in documenting the purpose of each enum member. ```yaml enum_style: "enum" ``` ```go // User role enumeration type Status = string const ( // Default status for new users StatusActive Status = "active" StatusInactive Status = "inactive" // User is temporarily disabled ) ``` ```typescript /** * User role enumeration */ export enum Status { /** * Default status for new users */ Active = "active", Inactive = "inactive", // User is temporarily disabled } ``` -------------------------------- ### Define Generic Structs with Value and Pointer Fields in TypeScript Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/generic.md Provides TypeScript interfaces that mirror Go's generic structs, supporting value and pointer-like fields with type constraints. ```typescript export interface ValAndPtr { Val: V; /** * Comment for ptr field */ Ptr: PT; // ptr line comment } export interface ABCD { a: A; b: B; c: C; d: D; } export interface Foo { Bar: A; Boo: B; } export interface WithFooGenericTypeArg> { some_field: A; } ``` -------------------------------- ### Mixed Constant Block with Union Enum (enum_style: "union") Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/enum.md Handles mixed constant blocks for union enums. Only string constants that are part of the enum are used to form the union type. ```yaml enum_style: "union" ``` ```go type UserRole = string const ( UserRoleAdmin UserRole = "admin" UserRoleGuest UserRole = "guest" MaxRetries = 5 DefaultTimeout = 30 ) ``` ```typescript export const UserRoleAdmin = "admin"; export const UserRoleGuest = "guest"; export type UserRole = typeof UserRoleAdmin | typeof UserRoleGuest; export const MaxRetries = 5; export const DefaultTimeout = 30; ``` -------------------------------- ### Constants with Comma Separation: TypeScript Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/simple.md Translates Go constants declared on a single line into separate TypeScript constant declarations. The inline comment is preserved for each translated constant. ```typescript export const Pi = 3.14; // A comment on constants separated by a comma export const E = 2.71; // A comment on constants separated by a comma ``` -------------------------------- ### Comment Preservation Setting Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/simple.md Specifies the comment preservation strategy as 'none'. This configuration affects how comments are handled during translation. ```yaml preserve_comments: "none" ``` -------------------------------- ### Emit String Literal as TypeScript Type Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/emit.md Use the `tygo:emit` directive on a string literal to emit that string's content as TypeScript code. This is useful for defining complex types or interfaces directly within Go source files. ```go // emit directive on a string literal emits that value. // //tygo:emit var _ = `export type OtherStructAsTuple=[ a:number, b:number, c:string, ] ` ``` -------------------------------- ### Inject Custom TypeScript with `//tygo:emit` Source: https://context7.com/gzuidhof/tygo/llms.txt The `//tygo:emit` directive injects literal TypeScript code. It can be used before a struct to emit text on the same comment line, or before a `var _ = `...`` declaration to emit string contents for multi-line types. ```go // Emit a multi-line type from a string literal //tygo:emit var _ = `export type OtherStructAsTuple=[ a:number, b:number, c:string, ] ` // Emit a single-line type before a struct //tygo:emit export type StructAsTuple=[a:number, b:number, c:string] type CustomMarshalled struct { Content []StructAsTuple `json:"content"` } //tygo:emit export type Genre = "novel" | "crime" | "fantasy" type Book struct { Title string `json:"title"` Genre string `json:"genre" tstype:"Genre"` } ``` ```typescript export type OtherStructAsTuple=[ a:number, b:number, c:string, ] export type StructAsTuple=[a:number, b:number, c:string] export interface CustomMarshalled { content: StructAsTuple[]; } export type Genre = "novel" | "crime" | "fantasy" export interface Book { title: string; genre: Genre; } ``` -------------------------------- ### TypeScript Output for Custom Type Mapping Source: https://github.com/gzuidhof/tygo/blob/main/README.md The resulting TypeScript interface generated from the Go struct with a custom `tstype` tag. ```typescript export interface Book { title: string; genre: "novel" | "crime" | "fantasy"; } ``` -------------------------------- ### Mixed Constant Block with Enum (enum_style: "enum") Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/enum.md Handles mixed constant blocks where some are part of the enum and others are separate constants. Only enum members are generated as TypeScript enums. ```yaml enum_style: "enum" ``` ```go type UserRole = string const ( UserRoleAdmin UserRole = "admin" UserRoleGuest UserRole = "guest" MaxRetries = 5 DefaultTimeout = 30 ) ``` ```typescript export enum UserRole { Admin = "admin", Guest = "guest", } export const MaxRetries = 5; export const DefaultTimeout = 30; ``` -------------------------------- ### Define Single Generic Type in TypeScript Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/generic.md Presents the TypeScript equivalent for a Go generic type, using interfaces and type aliases. ```typescript export interface Single { Field: S; } export type SingleSpecific = Single; ``` -------------------------------- ### TypeScript Output for Required Pointer Fields Source: https://github.com/gzuidhof/tygo/blob/main/README.md The resulting TypeScript interface showing optional and required fields, including those derived from pointer types. ```typescript export interface Nicknames { alice?: string; bob: BobCustomType; charlie: string; } ``` -------------------------------- ### Default Behavior (enum_style: "const") Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/enum.md When enum_style is set to 'const', string constants are generated for each Go constant, along with their type definitions. ```yaml enum_style: "const" ``` ```go type UserRole = string const ( UserRoleDefault UserRole = "viewer" UserRoleEditor UserRole = "editor" ) ``` ```typescript export type UserRole = string; export const UserRoleDefault: UserRole = "viewer"; export const UserRoleEditor: UserRole = "editor"; ``` -------------------------------- ### Define Generic Slice Type in TypeScript Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/generic.md Presents the TypeScript equivalent for a Go generic slice type, using array notation. ```typescript export type JsonArray = T[]; ``` -------------------------------- ### TypeScript Output with Emitted Type Source: https://github.com/gzuidhof/tygo/blob/main/README.md The TypeScript code generated, including the emitted `Genre` type and the `Book` interface. ```typescript export type Genre = "novel" | "crime" | "fantasy"; export interface Book { title: string; genre: Genre; } ``` -------------------------------- ### Emit Struct Definition as TypeScript Interface Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/emit.md When the `tygo:emit` directive is placed on a struct definition, it emits the remainder of the directive line as TypeScript code. This allows for custom type generation, such as mapping a Go struct field to a TypeScript tuple. ```go // CustomMarshalled illustrates getting tygo to emit literal text // This solves the problem of a struct field being marshalled into a tuple. // // emit directive on a struct emits the remainder of the directive line // //tygo:emit export type StructAsTuple=[a:number, b:number, c:string] type CustomMarshalled struct { Content []StructAsTuple `json:"content"` } ``` -------------------------------- ### Struct Translation with Comments: TypeScript Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/simple.md Translates the Go struct into a TypeScript interface, preserving comments and mapping fields. Imported types in Go are represented as 'any' in TypeScript with a comment indicating the original type. ```typescript /** * Comment for a struct */ export interface MyStruct { some_field: any; /** * Comment for a field */ OtherField: boolean; // Comment after line FieldWithImportedType: any /* some.Type */; } ``` -------------------------------- ### Type Definition with Inline Comment: TypeScript Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/simple.md Represents the Go type definition in TypeScript, translating the type and preserving the inline comment. The preceding comment from Go is omitted as per the 'none' preservation setting. ```typescript export type MyValue = number /* int */; ``` -------------------------------- ### Map Go Rune Type to TypeScript Number Source: https://context7.com/gzuidhof/tygo/llms.txt Go's `rune` type alias, which is equivalent to `int32`, is mapped to `number` in TypeScript. ```go // Go input type MyRune rune ``` ```typescript // TypeScript output export type MyRune = number /* int32 */; ``` -------------------------------- ### Generated TypeScript Types Source: https://github.com/gzuidhof/tygo/blob/main/tygo/testdata/fixtures/emit.md This section shows the TypeScript types generated by the `tygo:emit` directives in the Go code. It includes interfaces and union types corresponding to the Go struct definitions. ```typescript export type OtherStructAsTuple=[ a:number, b:number, c:string, ] ``` ```typescript export type StructAsTuple=[a:number, b:number, c:string] ``` ```typescript /** * CustomMarshalled illustrates getting tygo to emit literal text * This solves the problem of a struct field being marshalled into a tuple. * emit directive on a struct emits the remainder of the directive line */ export interface CustomMarshalled { content: StructAsTuple[]; } ``` ```typescript export type Genre = "novel" | "crime" | "fantasy" ``` ```typescript export interface Book { title: string; genre: Genre; } ``` -------------------------------- ### YAML Flavor: Lowercasing Untagged Fields Source: https://context7.com/gzuidhof/tygo/llms.txt When `flavor: "yaml"` is set, untagged struct field names are lowercased in the TypeScript output, mimicking `gopkg.in/yaml.v2` behavior. Fields with explicit `yaml:` tags are preserved. ```go // Go input — yaml/yaml.go (config: flavor: "yaml") type YAMLTest struct { ID string `yaml:"id"` Preferences map[string]struct { Foo uint32 `yaml:"foo"` } `yaml:"prefs"` MaybeFieldWithStar *string `yaml:"address"` Nickname string `yaml:"nickname,omitempty"` ThisWillGetLowercased string // no tag → lowercased by yaml flavor } ``` ```typescript // TypeScript output export interface YAMLTest { id: string; prefs: { [key: string]: { foo: number /* uint32 */; }}; address?: string; nickname?: string; thiswillgetlowercased: string; } ```