Skip to content

Commit 98a8c51

Browse files
authored
chore: prevent null in heritage extends expressions (#41)
This is a temporary workaround to generate valid typescript. This solution is not completely correct, and is subject to future change.
1 parent 91f6f37 commit 98a8c51

File tree

4 files changed

+25
-3
lines changed

4 files changed

+25
-3
lines changed

convert.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -650,8 +650,21 @@ func (ts *Typescript) buildStruct(obj types.Object, st *types.Struct) (*bindings
650650
// Adding a json struct tag causes the json package to consider
651651
// the field unembedded.
652652
if field.Embedded() && tag.Get("json") == "" {
653+
// TODO: This prevents an inheritance clause from having a ` | null` in the
654+
// expression. Typescript does not support `null` in the extends clause.
655+
// This is not a perfect solution, and exists as a workaround.
656+
// See https://github.com/coder/guts/issues/40
657+
fieldType := field.Type()
658+
for i := 0; i < 10; i++ { // Can there be an infinite loop here?
659+
if ptrType, ok := fieldType.(*types.Pointer); ok {
660+
fieldType = ptrType.Elem()
661+
continue
662+
}
663+
break
664+
}
665+
653666
// TODO: Generic args
654-
heritage, err := ts.typescriptType(field.Type())
667+
heritage, err := ts.typescriptType(fieldType)
655668
if err != nil {
656669
return tsi, xerrors.Errorf("heritage type: %w", err)
657670
}

testdata/excludecustom/excludecustom.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@
44
export interface Public {
55
readonly PublicString: string;
66
readonly PublicInt: number;
7-
}
7+
}

testdata/inheritance/inheritance.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@ type Foo struct {
55
GenBar[string]
66
}
77

8+
type FooBarPtr struct {
9+
*Bar
10+
GenBar[string]
11+
}
12+
813
type Bar struct {
914
BarField int
1015
}
@@ -17,7 +22,7 @@ type GenBar[T comparable] struct {
1722
// See: https://go.dev/play/p/-p6QYmY8mtR
1823
type FooBuzz struct {
1924
Buzz `json:"foo"` // Json tag changes the inheritance
20-
Bazz string `json:"bazz"`
25+
Bazz string `json:"bazz"`
2126
}
2227

2328
type Buzz struct {

testdata/inheritance/inheritance.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@ export type Comparable = string | number | boolean;
1616
export interface Foo extends Bar, GenBar<string> {
1717
}
1818

19+
// From codersdk/inheritance.go
20+
export interface FooBarPtr extends Bar, GenBar<string> {
21+
}
22+
1923
// From codersdk/inheritance.go
2024
export interface FooBuzz {
2125
readonly foo: Buzz;

0 commit comments

Comments
 (0)