Skip to content

Commit 6163ace

Browse files
committed
Support generics in apitypings
1 parent 0ecb427 commit 6163ace

File tree

1 file changed

+15
-7
lines changed

1 file changed

+15
-7
lines changed

scripts/apitypings/main.go

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -326,23 +326,26 @@ type structTemplateState struct {
326326
PosLine string
327327
Name string
328328
Fields []string
329+
Generics []string
329330
Extends string
330331
AboveLine string
331332
}
332333

333334
const structTemplate = `{{ .PosLine -}}
334335
{{ if .AboveLine }}{{ .AboveLine }}
335-
{{ end }}export interface {{ .Name }}{{ if .Extends }} extends {{ .Extends }}{{ end }}{
336-
{{- range .Fields }}
337-
{{ . -}}
338-
{{- end }}
336+
{{ end }}export interface {{ .Name }}{{ if .Generics }}<{{ join .Generics ", " }}>{{ end }}{{ if .Extends }} extends {{ .Extends }}{{ end }} {
337+
{{ join .Fields "\n"}}
339338
}
340339
`
341340

342341
// buildStruct just prints the typescript def for a type.
343342
func (g *Generator) buildStruct(obj types.Object, st *types.Struct) (string, error) {
344343
state := structTemplateState{}
345-
tpl, err := template.New("struct").Parse(structTemplate)
344+
tpl := template.New("struct")
345+
tpl.Funcs(template.FuncMap{
346+
"join": strings.Join,
347+
})
348+
tpl, err := tpl.Parse(structTemplate)
346349
if err != nil {
347350
return "", xerrors.Errorf("parse struct template: %w", err)
348351
}
@@ -428,7 +431,12 @@ func (g *Generator) buildStruct(obj types.Object, st *types.Struct) (string, err
428431
if jsonOptional || tsType.Optional {
429432
optional = "?"
430433
}
431-
state.Fields = append(state.Fields, fmt.Sprintf("%sreadonly %s%s: %s", indent, jsonName, optional, tsType.ValueType))
434+
valueType := tsType.ValueType
435+
if tsType.GenericMapping != "" {
436+
valueType = tsType.GenericMapping
437+
state.Generics = append(state.Generics, fmt.Sprintf("%s extends %s", tsType.GenericMapping, tsType.ValueType))
438+
}
439+
state.Fields = append(state.Fields, fmt.Sprintf("%sreadonly %s%s: %s", indent, jsonName, optional, valueType))
432440
}
433441

434442
data := bytes.NewBuffer(make([]byte, 0))
@@ -603,7 +611,7 @@ func (g *Generator) typescriptType(ty types.Type) (TypescriptType, error) {
603611

604612
generic := ty.Constraint()
605613
// This is kinda a hack, but we want just the end of the name.
606-
name := strings.TrimSuffix("github.com/coder/coder/codersdk.", generic.String())
614+
name := strings.TrimPrefix(generic.String(), "github.com/coder/coder/codersdk.")
607615
return TypescriptType{
608616
GenericMapping: ty.Obj().Name(),
609617
ValueType: name,

0 commit comments

Comments
 (0)