Skip to content

Commit f955150

Browse files
committed
Support generics in apitypings
1 parent 0e36824 commit f955150

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
}
@@ -432,7 +435,12 @@ func (g *Generator) buildStruct(obj types.Object, st *types.Struct) (string, err
432435
if jsonOptional || tsType.Optional {
433436
optional = "?"
434437
}
435-
state.Fields = append(state.Fields, fmt.Sprintf("%sreadonly %s%s: %s", indent, jsonName, optional, tsType.ValueType))
438+
valueType := tsType.ValueType
439+
if tsType.GenericMapping != "" {
440+
valueType = tsType.GenericMapping
441+
state.Generics = append(state.Generics, fmt.Sprintf("%s extends %s", tsType.GenericMapping, tsType.ValueType))
442+
}
443+
state.Fields = append(state.Fields, fmt.Sprintf("%sreadonly %s%s: %s", indent, jsonName, optional, valueType))
436444
}
437445

438446
data := bytes.NewBuffer(make([]byte, 0))
@@ -607,7 +615,7 @@ func (g *Generator) typescriptType(ty types.Type) (TypescriptType, error) {
607615

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

0 commit comments

Comments
 (0)