Skip to content

Commit e972977

Browse files
authored
fix(api): Don't render enums twice if they appear in separate objects
Fixes an issue with enums in which they're rendered for each object they appear in, instead of just once.
2 parents 8374a6c + 472f150 commit e972977

File tree

3 files changed

+43
-2
lines changed

3 files changed

+43
-2
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
declare namespace Api {
2+
interface TypeTwoWithEnum {
3+
anEnum: 'FirstEnum' | 'SecondEnum' | 'ThirdEnum';
4+
}
5+
interface TypeOneWithEnum {
6+
anEnum: 'FirstEnum' | 'SecondEnum' | 'ThirdEnum';
7+
}
8+
}
9+
10+
---
11+
enum SharedEnumType {
12+
FirstEnum = 'FirstEnum',
13+
SecondEnum = 'SecondEnum',
14+
ThirdEnum = 'ThirdEnum',
15+
}

src/Typescript.Tests/Enums/EnumGeneratorTests.cs

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
using System;
22
using Assent;
33
using Typescriptr;
4-
using Typescriptr.Formatters;
54
using Xunit;
65

76
namespace Typescript.Tests.Enums
@@ -74,5 +73,31 @@ public void Generator_TypeWithEnumAndEnumValueFormatter_RendersValues()
7473

7574
this.Assent(generated.JoinTypesAndEnums());
7675
}
76+
77+
78+
class TypeOneWithEnum
79+
{
80+
public SharedEnumType AnEnum { get; set; }
81+
}
82+
class TypeTwoWithEnum
83+
{
84+
public SharedEnumType AnEnum { get; set; }
85+
}
86+
87+
public enum SharedEnumType
88+
{
89+
FirstEnum,
90+
SecondEnum,
91+
ThirdEnum
92+
}
93+
94+
[Fact]
95+
public void Generator_TypesWithSharedEnum_ShouldOnlyGenerateTheEnumOnce()
96+
{
97+
var generator = TypeScriptGenerator.CreateDefault();
98+
var generated = generator.Generate(new[] {typeof(TypeOneWithEnum), typeof(TypeTwoWithEnum)});
99+
100+
this.Assent(generated.JoinTypesAndEnums());
101+
}
77102
}
78103
}

src/Typescriptr/TypeScriptGenerator.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,9 +160,10 @@ public GenerationResult Generate(IEnumerable<Type> types)
160160

161161
private void RenderEnum(StringBuilder builder, Type enumType)
162162
{
163+
if (_enumNames.Contains(enumType.FullName)) return;
163164
var enumString = _enumFormatter(enumType, _quoteStyle);
164165
builder.Append(enumString);
165-
_enumNames.Add(enumType.Name);
166+
_enumNames.Add(enumType.FullName);
166167
}
167168

168169
private void RenderType(StringBuilder builder, Type type)

0 commit comments

Comments
 (0)