Coder Social home page Coder Social logo

tygo's Introduction

๐ŸŽ‘ tygo

Tygo is a tool for generating Typescript typings from Golang source files that just works.

It preserves comments, understands constants and also supports non-struct type expressions. It's perfect for generating equivalent types for a Golang REST API to be used in your front-end codebase.

๐Ÿš€ Supports Golang 1.18 generic types and struct inheritance

Installation

go install github.com/gzuidhof/tygo@latest

Example

Golang input file

// 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"`

	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"`
}

Typescript output

/**
 * 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;
  complex: ComplexType;
}
export interface ListUsersResponse {
  users: UserEntry[];
}

For a real baptism by fire example, here is a Gist with output for the Go built-in net/http and time package.

Usage

Option A: CLI (recommended)

Create a file tygo.yaml in which you specify which packages are to be converted and any special type mappings you want to add.

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 */"

Then run

tygo generate

The output Typescript file will be next to the Go source files.

Option B: Library-mode

config := &tygo.Config{
  Packages: []*tygo.PackageConfig{
      &tygo.PackageConfig{
          Path: "github.com/gzuidhof/tygo/examples/bookstore",
      },
  },
}
gen := tygo.New(config)
err := gen.Generate()

Config

# You can specify more than one package
packages:
  # The package path just like you would import it in Go
  - path: "github.com/my/package"

    # Where this output should be written to.
    # If you specify a folder it will be written to a file `index.ts` within that folder. By default it is written into the Golang package folder.
    output_path: "webapp/api/types.ts"

    # Customize the indentation (use \t if you want tabs)
    indent: "    "

    # Specify your own custom type translations, useful for custom types, `time.Time` and `null.String`.
    # Be default unrecognized types will be `any`.
    type_mappings:
      time.Time: "string"
      my.Type: "SomeType"

    # This content will be put at the top of the output Typescript file, useful for importing custom types.
    frontmatter: |
      "import {SomeType} from "../lib/sometype.ts"

    # Filenames of Go source files that should not be included
    # in the output.
    exclude_files:
      - "private_stuff.go"

    # Package that the generates Typescript types should extend. This is useful when
    # attaching your types to a generic ORM.
    extends: "SomeType"

See also the source file tygo/config.go.

Type hints through tagging

You can tag struct fields with tstype to specify their output Typescript type.

Custom type mapping

// Golang input

type Book struct {
	Title    string    `json:"title"`
	Genre    string    `json:"genre" tstype:"'novel' | 'crime' | 'fantasy'"`
}
// Typescript output

export interface Book {
  title: string;
  genre: "novel" | "crime" | "fantasy";
}

Alternative

You could use the frontmatter field in the config to inject export type Genre = "novel" | "crime" | "fantasy" at the top of the file, and use tstype:"Genre". I personally prefer that as we may use the Genre type more than once.

tygo:emit directive

Another way to generate types that cannot be directly represented in Go is to use a //tygo:emit directive to directly emit literal TS code. The directive can be used in two ways. A tygo:emit directive on a struct will emit the remainder of the directive text before the struct.

// Golang input

//tygo:emit export type Genre = "novel" | "crime" | "fantasy"
type Book struct {
	Title    string    `json:"title"`
	Genre    string    `json:"genre" tstype:"Genre"`
}
export type Genre = "novel" | "crime" | "fantasy"

export interface Book {
  title: string;
  genre: Genre;
}

A //tygo:emit directive on a string var will emit the contents of the var, useful for multi-line content.

//tygo:emit
var _ = `export type StructAsTuple=[
  a:number, 
  b:number, 
  c:string,
]
`
type CustomMarshalled struct {
  Content []StructAsTuple `json:"content"`
}
export type StructAsTuple=[
  a:number, 
  b:number, 
  c:string,
]

export interface CustomMarshalled {
  content: StructAsTuple[];
}

Generating types this way is particularly useful for tuple types, because a comma cannot be used in the tstype tag.

Required fields

Pointer type fields usually become optional in the Typescript output, but sometimes you may want to require it regardless.

You can add ,required to the tstype tag to mark a pointer type as required.

// Golang input
type Nicknames struct {
	Alice   *string `json:"alice"`
	Bob     *string `json:"bob" tstype:"BobCustomType,required"`
	Charlie *string `json:"charlie" tstype:",required"`
}
// Typescript output
export interface Nicknames {
  alice?: string;
  bob: BobCustomType;
  charlie: string;
}

Readonly fields

Sometimes a field should be immutable, you can add ,readonly to the tstype tag to mark a field as readonly.

// Golang input
type Cat struct {
	Name    string `json:"name,readonly"`
	Owner   string `json:"owner"`
}
// Typescript output
export interface Cat {
  readonly name: string;
  owner: string;
}

Inheritance

Tygo supports interface inheritance. To extend an inlined struct, use the tag tstype:",extends" on struct fields you wish to extend. Only struct types can be extended.

Struct pointers are optionally extended using Partial<MyType>. To mark these structs as required, use the tag tstype:",extends,required".

Named struct fields can also be extended.

Example usage here

// Golang input
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 output
export interface Base {
  name: string;
}

export interface Base2<T extends string | number /* int */> {
  id: T;
}

export interface OptionalPtr {
  field: string;
}

export interface Other<T extends number /* int */>
  extends Base,
    Base2<T>,
    Partial<OptionalPtr>,
    external.AnotherStruct {
  other_value: string;
}

Generics

Tygo supports generic types (Go version >= 1.18) out of the box.

// Golang input
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 output
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;
}

YAML support

Tygo supports generating typings for YAML-serializable objects that can be understood by Go apps.

By default, Tygo will respect yaml Go struct tags, in addition to json, but it will not apply any transformations to untagged fields. However, the default behavior of the popular gopkg.in/yaml.v2 package for Go structs without tags is to downcase the struct field names. To emulate this behavior, one can use the flavor configuration option:

packages:
  - path: "github.com/my/package"
    output_path: "webapp/api/types.ts"
    flavor: "yaml"
// Golang input
type Foo struct {
	TaggedField string `yaml:"custom_field_name_in_yaml"`
    UntaggedField string
}
// Typescript output
export interface Foo {
  custom_field_name_in_yaml: string;
  untaggedfield: string;
}

Related projects

  • typescriptify-golang-structs: Probably the most popular choice. The downside of this package is that it relies on reflection rather than parsing, which means that certain things can't be kept such as comments without adding a bunch of tags to your structs. The CLI generates a Go file which is then executed and reflected on. The library requires you to manually specify all types that should be converted.
  • go2ts: A transpiler with a web interface, this project can be seen as an evolution of this project. It's perfect for quick one-off transpilations. There is no CLI, no support for const and there are no ways to customize the output.

If tygo is useful for your project, consider leaving a star.

License

MIT

tygo's People

Contributors

brianstarke avatar cmoog avatar greyscaled avatar gzuidhof avatar imiric avatar jor-rit avatar lxnre-codes avatar mlafeldt avatar moeshin avatar mtt0 avatar ogreeni avatar pdhammond42 avatar slinso avatar tyler-proofserve-com avatar volkerlieber avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

tygo's Issues

Interface type definitions return broken types

If I define an interface with methods, the type returned is broken. For example:

type DeploymentService interface {

  CreateDeployment(ctx context.Context, input CreateDeploymentInput)
  ....
}

Will return the following ill-formatted type such as:

export type DeploymentService = 
;

Which shows as an error in TS.

Ideally, it should return an empty type or no type at all (skip processing, I believe).

Otherwise, fantastic library and it's a big help.

Directive comments on type/const statements break generation

Description:

Attempting to generate TS on type/const statements with go directives (or comments that match the directive regex) e.g. type X int //revive:disable-line:exported can cause improper TS code to be generated. The generated TS ends up including a // at the beginning of a comment without any text and no newline, such that if the next generated code is a block comment, its /** prefix is commented out causing broken code. (See example below for more clarity).

Analysis:

I've traced the issue to writing the comments on type (and likewise line 182). When the comment is a directive,{spec}.Comment.Text() is an empty string, there is no newline being added at the end of the comment which would usually be there. So when the next generated code is a block comment it begins on the same line as a single line comment.

One suggestion to fix this would be to check that {spec}.Comment.Text() is not empty on top of {spec}.Comment != nil. This would then not even add an empty // if there is a directive. Would you be able to make this change? Or accept a PR to make this fix?

Example:

indexer.go

package indexer

const SomeValue = 3 //comment:test

// 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
)

Generated index.ts, note the occurrences of // /** which breaks the block comments

// Code generated by tygo. DO NOT EDIT.

//////////
// source: indexer.go

export const SomeValue = 3; // /**
 * 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

tygo.yaml

packages:
  - path: "indexer"

Fix goreleaser config

The latest Github Actions run is broken, I think the config needs to be updated as we were using some outdated config fields that have now been removed.

Go generate comments

As an extension of #11, it would be nice in my code select which types I want generated, could perhaps be done with //generate: xx comments, or some other style

Structs are not properly embedded inside types/Composition is not handled properly

When a struct is embedded inside a type, the generated TypeScript definition for that type produces a key/value pair where the key and value are named after the struct, instead of inlining the fields of the struct inside the type.

Here's an example:

tygo.yaml:

  - path: 'github.com/Drelf2018/req'

Generated TS output:

// Code generated by tygo. DO NOT EDIT.

//////////
// source: client.go

export const Omitempty: string = "omitempty";
export const UserAgent: string = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.54";
export interface Client {
  Client: any /* http.Client */;
  BaseURL?: any /* url.URL */;
  Header: any /* http.Header */;
  /**
   * Client will use the value in Variables when the Field's Value starts with "$"
   */
  Variables: { [key: string]: any};
}

//////////
// source: encode.go

export type Marshaler = any;

//////////
// source: interfaces.go

export type Api = any;
export interface Get {
}
export interface Post {
}
export interface PostForm {
  Post: Post;
}
export interface PostJson {
  Post: Post;
}
export type Adder = any;
export type NamedReader = 
    any /* io.Reader */;
export type Unwrap = any;
export type BeforeRequest = any;

//////////
// source: task.go

export interface Field {
  /**
   * index in Api struct
   */
  Index: number /* int */[];
  /**
   * provided by json tag or parsed from the field name
   */
  Key: string;
  /**
   * default value used when the field value is zero
   */
  Value: string;
  /**
   * This field is ignored when it is zero, conflict with default value
   */
  Omit: boolean;
}
export interface Task {
  Body: Field[];
  Files: Field[];
  Query: Field[];
  Header: Field[];
}
export interface Any {
  Type: any /* unsafe.Pointer */;
  Value: any /* unsafe.Pointer */;
}

My knowledge of Go is beginner level, so apologies if I got something wrong. If I understand correctly, the type PostForm should be empty in terms of its generated fields (it is composed of Post).

Does not support enums

This doesn't work, it doesn't generate correct types.

// MessageNotifications is the notification level for a guild
// https://discord.com/developers/docs/resources/guild#guild-object-default-message-notification-level
type MessageNotifications int

// Block containing known MessageNotifications values
const (
	MessageNotificationsAllMessages  MessageNotifications = 0
	MessageNotificationsOnlyMentions MessageNotifications = 1
)

// SystemChannelFlag is the type of flags in the system channel (see SystemChannelFlag* consts)
// https://discord.com/developers/docs/resources/guild#guild-object-system-channel-flags
type SystemChannelFlag int

// Block containing known SystemChannelFlag values
const (
	SystemChannelFlagsSuppressJoinNotifications          SystemChannelFlag = 1 << 0
	SystemChannelFlagsSuppressPremium                    SystemChannelFlag = 1 << 1
	SystemChannelFlagsSuppressGuildReminderNotifications SystemChannelFlag = 1 << 2
	SystemChannelFlagsSuppressJoinNotificationReplies    SystemChannelFlag = 1 << 3
)

`TypeMappings` usage

Given the following simple example.

Input

packages:
  - path: "types/src/test"
    output_path: "src/types.ts"
    type_mappings:
      types.TestType: "number"
package types

type TestType string

Output

// Code generated by tygo. DO NOT EDIT.

//////////
// source: types.go

export type TestType = string;

Any help with the TypeMappings feature would be appreciated.

Includes (list of files)

It would be great to be able to include not the whole package but list of files. I'm aware of "exclude" option but if package is big and I only need 1 file from it, it's error-prone (go package can be changed, list of files it contains changes)

Use with local files

Sorry for a silly question, but how would I go about using this lib to convert .go files to .ts specifying a directory, that consists of said go files, instead of packages?
I am trying to supply a local dir to it, but it appears to be trying to query github.com for the package

Generic type with `any` in Golang not working

I have:

//Go
type FeEnum[T any] struct {
	Value  T
	TSName string
}

After generate I got:

//TypeScript
export interface FeEnum<T extends > { //<=== missing `any` here!!!!
  Value: T;
  TSName: string;
}

instantiated error types not being generated/outputted

type ErrNotFound error

var (
	ErrFoodNotFound            ErrNotFound = errors.New("food not found")
	ErrCompanyNotFound           ErrNotFound = errors.New("company not found")
	ErrUserNotFound            ErrNotFound = errors.New("user not found")
)

output:

export type ErrNotFound = error;

I am trying to use this common pattern in go, but none of the instantiated errors are being generated
Is there a work around for this @gzuidhof

Pointer types always translated as optional variables

I noticed that pointers are always translated to TS using ?.

For example:

type FollowerEvent struct {
	Follower            *twitter.User `json:"follower"`
}

Becomes:

export interface FollowerEvent {
  follower?: any /* twitter.User */;
}

While it's true that pointers are often used to express optional values, they're also used for e.g. efficiency reasons and the value might be "guaranteed" to be set.

Is there any way to remove the ? for pointer types from the generated TS?

Remove comments

It would be great to be able to generate TS file without comments

Support setting fields to optional

I've noticed that fields can be set to required by adding ,required to the struct tag. Is there a similar way to mark fields as optional? I specifically don't want to add omitempty or set the field to a pointer. My field is an array, and omitempty causes issues because it omits an empty array ([]) in addition to null, and I'd like to handle the two cases separately in my app.
Thanks!

TypeScript enum support

Hello. Awesome package :) Quick question. Are you planning to support TypeScript enums? These can be transformed to TS enums.

type UserRole = string
const (
	UserRoleDefault UserRole = "viewer"
	UserRoleEditor  UserRole = "editor" // Line comments are also kept
)

Thanks
Peter

Unwrapping / extending inline structs

Structs that are tagged as inline should be unwrapped.

// Input
type Vehicle struct {
	Category string `json:"category"`
	Make     string `json:"make"`
}

type Toyota struct {
	Vehicle `    json:",inline" tstype:",inline"`
	Year    int `json:"year"`
}
//Output
interface Vehicle {
  category: string;
  make: string;
}

interface Toyota extends Vehicle {
  year: number;
}

//Or 
interface Toyota  {
  category: string;
  make: string;
  year: number;
}

Feature request `TSType()` Method returning the tstype

Similar to the String() method.

type MyType struct {
   custom CustomType // the struct tag `tstype:"'string1' | 'string2'" is not needed anymore
}
type CustomType struct {
  field1 string
  field2 string
}
func (c CustomType) TSType() string {
  return "'string1' | 'string2'"
}

Option to not preserve comments

Context

By default, tygo preserves comments. So for example:

user.go
// package user does xyz
package user

type User struct {
  name: string
}

will generate output like:

//////////
// source: users.go
// package user does xyz

export interface User {
  name: string;
}

This is cool behavior, but sometimes it's not desired. Therefore, I think there should be an option
for suppressing comments that do not exist on types. The default would still be to preserve.

Expected

A config like this:

packages:
  - path: "<path>"
    output_path: "<output_path>"
    preserveComments: false # true or false, defaults to true

So that Go code like this:

user.go
// package user does xyz
package user

// secret is a secret
const secret = "secret"

type User struct {
  // name is a name
  name: string
}

produces TS like this:

//////////
// source: users.go

export interface User {
  /**
   * name is a name
   */
  name: string;
}

Actual

All comments are preserved and there's no option to suppress this behavior

Embedded structs

If I have a struct embedded such as

type A struct {
  FieldA string `json:"fieldA"`
}

type B struct {
  A
  FieldB string `json:"fieldB"`
}

This will product the json:

{"fieldA": "abc", "fieldB": "123"}

However the tygo type looks like this:

export interface A {
  fieldA: string;
}
export interface B {
  A: A;
  fieldB: string;
}

which is incorrect. Is there a way to get it to understand the embedded struct is flattened in the json?

Runes are not converted to numbers

Given the following simple example shouldn't rune be converted to a number?

Input

packages:
  - path: "types/src/test"
    output_path: "src/types.ts"
    type_mappings:
      time.Time: "string /* fancy comment */"
package types

import "time"

type TestType string

type TestRune rune

type TestRunes []rune

type TestStruct struct {
	SomeRune *rune
	SomeTime *time.Time
}

Output

// Code generated by tygo. DO NOT EDIT.

//////////
// source: types.go

export type TestType = string;
export type TestRune = rune;
export type TestRunes = rune[];
export interface TestStruct {
  SomeRune?: rune;
  SomeTime?: string /* fancy comment */;
}

From TS to Go?

Hi there, library looks great! Wondering if you'd thought about going the other way around? Generating typescript interfaces from Go interfaces/structs?

Crash when constant is negative

package test_tygo

const A = -1
> tygo generate
unhandled unary expr: &{32 - 0xc00020aa40}
 *ast.UnaryExpr
panic: unhandled unary expr: &{32 - 0xc00020aa40}
 *ast.UnaryExpr

goroutine 1 [running]:
github.com/gzuidhof/tygo/tygo.(*PackageGenerator).writeType(0xc000208690, 0xc000087168, {0x69cd60?, 0xc00020aa60?}, 0x0, 0x8?)
        C:/Users/MoeShin/go/pkg/mod/github.com/gzuidhof/[email protected]/tygo/write.go:114 +0x20a8
github.com/gzuidhof/tygo/tygo.(*PackageGenerator).writeValueSpec(0xc000208690, 0xc00020aa80, 0xc000258000, 0xc000087260)
        C:/Users/MoeShin/go/pkg/mod/github.com/gzuidhof/[email protected]/tygo/write_toplevel.go:204 +0xb9b
github.com/gzuidhof/tygo/tygo.(*PackageGenerator).writeSpec(0xc000230100?, 0x3f?, {0x69cb80?, 0xc000258000?}, 0x510bfe?)
        C:/Users/MoeShin/go/pkg/mod/github.com/gzuidhof/[email protected]/tygo/write_toplevel.go:65 +0xd5
github.com/gzuidhof/tygo/tygo.(*PackageGenerator).writeGroupDecl(0xc000208690, 0xc00020aa80?, 0xc000230100?)
        C:/Users/MoeShin/go/pkg/mod/github.com/gzuidhof/[email protected]/tygo/write_toplevel.go:51 +0xfe
github.com/gzuidhof/tygo/tygo.(*PackageGenerator).Generate.func1({0x69b9a0?, 0xc0002220c0?})
        C:/Users/MoeShin/go/pkg/mod/github.com/gzuidhof/[email protected]/tygo/package_generator.go:38 +0xcc
go/ast.inspector.Visit(0xc0002580a0, {0x69b9a0?, 0xc0002220c0?})
        C:/Users/MoeShin/scoop/apps/go/current/src/go/ast/walk.go:386 +0x2b
go/ast.Walk({0x69ad58?, 0xc0002580a0?}, {0x69b9a0?, 0xc0002220c0?})
        C:/Users/MoeShin/scoop/apps/go/current/src/go/ast/walk.go:51 +0x5c
go/ast.walkDeclList(...)
        C:/Users/MoeShin/scoop/apps/go/current/src/go/ast/walk.go:38
go/ast.Walk({0x69ad58?, 0xc0002580a0?}, {0x69b978?, 0xc00024a0a0?})
        C:/Users/MoeShin/scoop/apps/go/current/src/go/ast/walk.go:366 +0x1b05
go/ast.Inspect(...)
        C:/Users/MoeShin/scoop/apps/go/current/src/go/ast/walk.go:397
github.com/gzuidhof/tygo/tygo.(*PackageGenerator).Generate(0xc000208690)
        C:/Users/MoeShin/go/pkg/mod/github.com/gzuidhof/[email protected]/tygo/package_generator.go:24 +0x532
github.com/gzuidhof/tygo/tygo.(*Tygo).Generate(0xc000087b58)
        C:/Users/MoeShin/go/pkg/mod/github.com/gzuidhof/[email protected]/tygo/generator.go:65 +0x26e
github.com/gzuidhof/tygo/cmd.generate(0xc0000b0a00?, {0x619c5a?, 0x4?, 0x619c5e?})
        C:/Users/MoeShin/go/pkg/mod/github.com/gzuidhof/[email protected]/cmd/root.go:45 +0x110
github.com/spf13/cobra.(*Command).execute(0xc000071680, {0x8de700, 0x0, 0x0})
        C:/Users/MoeShin/go/pkg/mod/github.com/spf13/[email protected]/command.go:860 +0x67b
github.com/spf13/cobra.(*Command).ExecuteC(0xc000071400)
        C:/Users/MoeShin/go/pkg/mod/github.com/spf13/[email protected]/command.go:974 +0x38d
github.com/spf13/cobra.(*Command).Execute(...)
        C:/Users/MoeShin/go/pkg/mod/github.com/spf13/[email protected]/command.go:902
github.com/gzuidhof/tygo/cmd.Execute()
        C:/Users/MoeShin/go/pkg/mod/github.com/gzuidhof/[email protected]/cmd/root.go:31 +0x2be
main.main()
        C:/Users/MoeShin/go/pkg/mod/github.com/gzuidhof/[email protected]/main.go:6 +0xf

`iota` with Expressions

package test_tygo

const (
	A = iota
	B
)

const (
	C = 1 << iota
	D
)
// Code generated by tygo. DO NOT EDIT.

//////////
// source: type.go

export const A = 0;
export const B = 1;
export const C = 1 << iota;
export const D = 1 << iota;

Generate fields for types that are composed of subtypes

Hi! Thank you for your generator!

I'm trying to generate types where I have a type that is composed of subtypes. Is there something I can do in order for this to work.

Example:

type Base struct {
    Name   string  `json:"name"`
}

type Other struct {
    Base
    OtherField  string `json:"otherField"`
}

Expected output:

export interface Other {
  name: string;
  otherField: string;
}

multiple files

Would it be possible to add a config option to allow types on different files to be in different ts files

e.g if theres foo.go and bar.go in a package, create foo.ts and bar.ts for types instead of one file

Use Record or mapped types for map

I'd like to be able to generate either a Record or a typescript mapped type for a golang map type.

Example:

CheapestReturnMiles map[util.CabinClassT]util.MilesTax `json:"CheapestReturnMiles"`

Config:

type_mappings:
  util.CabinClassT: 'CabinClass'
  util.MilesTax: '{miles: number, tax: number}'

Current output:

CheapestReturnMiles: { [key: CabinClass]: {miles: number, tax: number}};

Expected output:

CheapestReturnMiles: Record<CabinClass, { miles: number; tax: number }>;

The current output fails typescript compliation, since we have CabinClass defined as type CabinClass = 'Economy' | 'First', and typescript doesnt allow literal types as index signatures.

Alternatively a mapped type could be used here:

CheapestReturnMiles: { [key in CabinClass]: { miles: number; tax: number } };

Usage with local checked out repo

How do I use tygo with a local checked out golang repo with go modules. My go.mod has

module github.com/name/reponame

In the config file I tried

packages:

  • path: 'github.com/name/reponame'

=> Tygo failed: [-: no required module provides package github.com/name/reponame; to add it:
go get github.com/name/reponame]

packages:

  • path: '.'

=> Tygo failed: [-: no Go files in /workspace/src/reponame]

packages:

  • path: './...'

=> Config not found for package github.com/name/reponame/subdir

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.