TypeLite e T4TS sopra sembravano buoni, ne ho appena scelto uno, TypeLite, l'ho biforcato per ottenere supporto per
- ValueTypes ,
- nullables
- camelCasing (il documento radice di TypeScript usa i cammelli, e questo va troppo bene insieme a C #)
- campi pubblici (adoro i POCO puliti e leggibili, facilita anche il compilatore C #)
- disabilita la generazione del modulo
Poi avevo bisogno di interfacce C # e ho pensato che fosse ora di creare qualcosa di mio e ho scritto un semplice script T4 che fa proprio quello che mi serve. Include anche Enums . Nessun repo richiesto, solo <100 righe di T4.
Utilizzo
Nessuna libreria, nessun NuGet, solo questo semplice file T4 semplice: usa "aggiungi elemento" in Visual Studio e scegli un modello T4 qualsiasi. Quindi incollalo nel file. Adatta ogni riga con "ACME" al suo interno. Per ogni classe C # aggiungi una riga
<#= Interface<Acme.Duck>() #>
L'ordine è importante, qualsiasi tipo noto verrà utilizzato nelle seguenti interfacce. Se si utilizzano solo interfacce, l'estensione del file può essere .d.ts , per le enumerazioni è necessario un file .ts , poiché viene istanziata una variabile.
Personalizzazione
Hack lo script.
<#@ template debug="true" hostSpecific="true" language="C#" #>
<#@ output extension=".ts" #>
<#@ Assembly Name="System.Core.dll" #>
<#@ assembly name="$(TargetDir)ACME.Core.dll" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Linq" #>
<#= Interface<Acme.Bunny>() #>
<#= Interface<Acme.Duck>() #>
<#= Interface<Acme.Birdy>() #>
<#= Enums<Acme.CarrotGrade>() #>
<#= Interface<Acme.LinkParticle>() #>
<#+
List<Type> knownTypes = new List<Type>();
string Interface<T>()
{
Type t = typeof(T);
var sb = new StringBuilder();
sb.AppendFormat("interface {0} {{\n", t.Name);
foreach (var mi in GetInterfaceMembers(t))
{
sb.AppendFormat(" {0}: {1};\n", this.ToCamelCase(mi.Name), GetTypeName(mi));
}
sb.AppendLine("}");
knownTypes.Add(t);
return sb.ToString();
}
IEnumerable<MemberInfo> GetInterfaceMembers(Type type)
{
return type.GetMembers(BindingFlags.Public | BindingFlags.Instance)
.Where(mi => mi.MemberType == MemberTypes.Field || mi.MemberType == MemberTypes.Property);
}
string ToCamelCase(string s)
{
if (string.IsNullOrEmpty(s)) return s;
if (s.Length < 2) return s.ToLowerInvariant();
return char.ToLowerInvariant(s[0]) + s.Substring(1);
}
string GetTypeName(MemberInfo mi)
{
Type t = (mi is PropertyInfo) ? ((PropertyInfo)mi).PropertyType : ((FieldInfo)mi).FieldType;
return this.GetTypeName(t);
}
string GetTypeName(Type t)
{
if(t.IsPrimitive)
{
if (t == typeof(bool)) return "bool";
if (t == typeof(char)) return "string";
return "number";
}
if (t == typeof(decimal)) return "number";
if (t == typeof(string)) return "string";
if (t.IsArray)
{
var at = t.GetElementType();
return this.GetTypeName(at) + "[]";
}
if(typeof (System.Collections.IEnumerable).IsAssignableFrom(t))
{
var collectionType = t.GetGenericArguments()[0]; // all my enumerables are typed, so there is a generic argument
return GetTypeName(collectionType) + "[]";
}
if (Nullable.GetUnderlyingType(t) != null)
{
return this.GetTypeName(Nullable.GetUnderlyingType(t));
}
if(t.IsEnum) return "number";
if(knownTypes.Contains(t)) return t.Name;
return "any";
}
string Enums<T>() // Enums<>, since Enum<> is not allowed.
{
Type t = typeof(T);
var sb = new StringBuilder();
int[] values = (int[])Enum.GetValues(t);
sb.AppendLine("var " + t.Name + " = {");
foreach(var val in values)
{
var name = Enum.GetName(typeof(T), val);
sb.AppendFormat("{0}: {1},\n", name, val);
}
sb.AppendLine("}");
return sb.ToString();
}
#>
Il livello successivo dello script consisterà nel creare l'interfaccia del servizio dalla classe MVC JsonController.