Skip to content

Advice: bringing objects back into Go #92

@jphastings

Description

@jphastings

I'd like to use tygo to be able to define TypeScript plugins for my Go code. I think this is a particularly powerful use of tygo, and I'm looking for advice around whether this is a suitable use, and/or encouragement to build a PR to make this a feature others can easily use.


My current (& working part of my) approach is:

  • Define a type in Go. For example:
    type Example struct { 
      Title string        `json:"title"`
      Act   goja.Callable `json:"act" tstype:"(string) => string"`
    }
  • Use tygo to export that type as an interface in an index.d.ts file, including a frontmatter:
    declare global {
      function capitalise(string): string
    }
    
    //////////
    // source: types.go
    
    export interface Example {
      title: string;
      act: (string) => string;
    }
  • Create my 'plugin' file:
    import { capitalise, Example } from "plugin-helpers"
    
    const example: Example = {
      title: "An example",
      act: (in: string) => `${capitalise(in)} ← is capitalised`,
    }
    export default example
    Note: I need to have a tsconfig.json file next to my plugin that maps the "plugin-helpers" path to my tygo-exported definitions file, so my IDE correctly identifies the type of capitalise, the Example interface, and anything else I make available from Go.

Now when my Go code is running I should be able to (still implementing):

  • Use go-typescript to transpile the plugin TypeScript to JS
  • Create a goja VM
  • Attach my whateverHelper function (and anything else I define in my tygo frontmatter) so it's available to the plugin typescript
  • ❓ Perhaps prepare an object for my export to be exported into?
  • Execute the transpiled "plugin" code in the VM
  • 🚨 (not sure how to do this!) Cast the exported Example object back into the Example struct, so I can interact with it:
    fmt.Println(example.Title)
    // => An example
    fmt.Println(example.Act(goja.Undefined(), "wibble"))
    // => WIBBLE ← is capitalised

If you got this far, thank you! Do you like the sound of what I'm suggesting? Do you have any advice on what I'm trying to do? On generalizing it to add as a PR to the tygo package?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions