Skip to content
/ go2ts Public

Convert golang types to Typescript declarations.

License

Notifications You must be signed in to change notification settings

alanshaw/go2ts

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

go2ts

Build Status Coverage Standard README pkg.go.dev reference golang version Go Report Card

Convert golang types to Typescript declarations.

Note:

  • chan T is converted to AsyncIterable<T>.
  • Interfaces are converted to any.
  • struct methods are NOT converted, but Converter.ConfigureFunc can be used to create method declarations.
  • Recursion is NOT supported.
  • By default:
    • Assumes functions/methods are async so return values are all Promise<T> and errors assumed to be thrown not returned.
    • context.Context in function parameters is ignored.
    • If a function returns multiple values they are returned as an array.

Install

go get github.com/alanshaw/go2ts

Usage

Example

package main

import (
  "reflect"
  "github.com/alanshaw/go2ts"
)

type User struct {
  Name string
}

func main () {
  c := go2ts.NewConverter()

  c.Convert(reflect.TypeOf("")) // string
  c.Convert(reflect.TypeOf(User{})) // { Name: string }
  c.Convert(reflect.TypeOf(func(string, int, bool) User { return nil })
  // (str: string, int: number, bool: boolean) => Promise<{ Name: string }>

  // Add custom type declarations
  c.AddTypes(map[reflect.Type]string{
    reflect.TypeOf(User{}): "User"
  })

  // Output now includes "User" instead of { Name: string }
  c.Convert(reflect.TypeOf(map[string]User{})) // { [k: string]: User }

  // Configuration for the function declarations:
  c.ConfigureFunc = func(t reflect.Type) FuncConf {
    return FuncConf{
      IsSync: true, // do not wrap return values in Promise<T>
      AlwaysArray: true, // always return an array of return values even if there's only 1
      NoIgnoreContext: true, // don't ignore the context.Context param
      ParamNames: []string{"ctx"}, // ordered parameter names
      // Also...
      // IsMethod: true,
      // MethodName: "MyMethod"
    }
  }
  c.Convert(reflect.TypeOf(func(context.Context) User { return nil })
  // (ctx: any) => [User]
}

API

pkg.go.dev Reference

Contribute

Feel free to dive in! Open an issue or submit PRs.

License

MIT © Alan Shaw

About

Convert golang types to Typescript declarations.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages