Skip to content

Commit

Permalink
Merge pull request #32 from gzuidhof/fix-interface-types
Browse files Browse the repository at this point in the history
Fix "empty" interfaces
  • Loading branch information
gzuidhof authored Aug 16, 2023
2 parents 528a9a2 + 73b02e8 commit 141134b
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 1 deletion.
9 changes: 9 additions & 0 deletions examples/interface/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Code generated by tygo. DO NOT EDIT.

//////////
// source: interface.go

/**
* Plain interfaces should output the unknown type, which is `any` by default but can also be configured as `unknown`).
*/
export type InterfaceOnly = any;
6 changes: 6 additions & 0 deletions examples/interface/interface.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package interfaceoutput

// Plain interfaces should output the unknown type, which is `any` by default but can also be configured as `unknown`).
type InterfaceOnly interface {
InterfaceMethod() string
}
3 changes: 3 additions & 0 deletions tygo.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,6 @@ packages:
- path: "github.com/gzuidhof/tygo/examples/yaml"
output_path: "./examples/yaml/index.ts"
flavor: "yaml"
- path: "github.com/gzuidhof/tygo/examples/interface"


14 changes: 13 additions & 1 deletion tygo/write.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,15 +148,23 @@ func (g *PackageGenerator) writeTypeParamsFields(s *strings.Builder, fields []*a
}

func (g *PackageGenerator) writeInterfaceFields(s *strings.Builder, fields []*ast.Field, depth int) {
// Usually interfaces in Golang don't have fields, but generic (union) interfaces we can map to Typescript.

if len(fields) == 0 { // Type without any fields (probably only has methods)
s.WriteString(g.conf.FallbackType)
return
}
s.WriteByte('\n')

didContainNonFuncFields := false
for _, f := range fields {
if _, isFunc := f.Type.(*ast.FuncType); isFunc {
continue
}
if !didContainNonFuncFields {
s.WriteByte('\n') // We need to write a newline so comments of generic components render nicely.
didContainNonFuncFields = true
}

if g.PreserveTypeComments() {
g.writeCommentGroupIfNotNil(s, f.Doc, depth+1)
}
Expand All @@ -168,6 +176,10 @@ func (g *PackageGenerator) writeInterfaceFields(s *strings.Builder, fields []*as
s.WriteString(f.Comment.Text())
}
}

if !didContainNonFuncFields {
s.WriteString(g.conf.FallbackType)
}
}

func (g *PackageGenerator) writeStructFields(s *strings.Builder, fields []*ast.Field, depth int) {
Expand Down

0 comments on commit 141134b

Please sign in to comment.