-
Notifications
You must be signed in to change notification settings - Fork 25
/
TypeFunctions.ToTypeScriptDefault.cs
69 lines (67 loc) · 2.17 KB
/
TypeFunctions.ToTypeScriptDefault.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NTypewriter.CodeModel.Functions
{
/// <summary>
/// Set of functions that operates on IType
/// </summary>
public static partial class TypeFunctions
{
/// <summary>
/// The default value of the type.
/// (Dictionary types returns {}, enumerable types returns [],
/// boolean types returns false, numeric types returns 0, void returns void(0),
/// Guid types return empty guid string, Date types return new Date(0),
/// all other types return null)
/// </summary>
public static string ToTypeScriptDefault(this IType type)
{
if (type.IsNullable)
{
if (!((type is ITypeReferencedByMember typeReference) && (typeReference.Parent?.Attributes.Any(x => x.Name == "Required")) == true))
{
return "null";
}
else
{
type = type.TypeArguments.FirstOrDefault() ?? type;
}
}
if (type.IsEnum)
{
return "0";
}
switch (type.FullName)
{
case "System.Boolean":
return "false";
case "System.String":
case "System.Char":
return "\"\"";
case "System.Guid":
return "\"00000000-0000-0000-0000-000000000000\"";
case "System.Byte":
case "System.SByte":
case "System.Int16":
case "System.Int32":
case "System.Int64":
case "System.UInt16":
case "System.UInt32":
case "System.UInt64":
case "System.Single":
case "System.Double":
case "System.Decimal":
return "0";
case "System.Void":
return "void(0)";
}
if (type.IsEnumerable)
{
return "[]";
}
return "{}";
}
}
}