Skip to content

Commit 2ca9209

Browse files
authored
jsgen: fix alias type initalization (fix #24475) (#24480)
1 parent 9834bb0 commit 2ca9209

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

vlib/v/gen/js/builtin_types.v

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,12 @@ fn (mut g JsGen) copy_val(t ast.Type, tmp string) string {
2222
}
2323

2424
fn (mut g JsGen) to_js_typ_val(t ast.Type) string {
25-
sym := g.table.sym(t)
25+
sym := g.table.sym(g.table.unaliased_type(t))
2626
mut styp := ''
2727
mut prefix := 'new '
28+
if sym.info is ast.SumType {
29+
return g.to_js_typ_val(sym.info.variants[0])
30+
}
2831
match sym.kind {
2932
.i8, .i16, .int, .i64, .u8, .u16, .u32, .u64, .f32, .f64, .int_literal, .float_literal {
3033
styp = '${prefix}${g.sym_to_js_typ(sym)}(0)'

vlib/v/gen/js/tests/alias.v

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
type Type0 = string
2+
type Type1 = int | string
3+
type Type2 = string | int
4+
5+
struct Foo {
6+
field_0 Type0
7+
field_1 Type1
8+
field_2 Type2
9+
}
10+
11+
fn main() {
12+
foo := Foo{}
13+
14+
// checks alias types
15+
assert foo.field_0 == ''
16+
17+
// checks sum types
18+
if foo.field_1 is int {
19+
assert foo.field_1 == 0
20+
} else {
21+
assert false
22+
}
23+
24+
// checks sum types
25+
if foo.field_2 is string {
26+
assert foo.field_2 == ''
27+
} else {
28+
assert false
29+
}
30+
}

0 commit comments

Comments
 (0)