TypeLite et T4TS ci-dessus avaient l'air bien, je n'en ai choisi qu'un, TypeLite, l'a fourchu pour obtenir du soutien pour
- ValueTypes ,
- Nullables
- camelCasing (la documentation racine de TypeScript utilise des chameaux, et cela va trop bien avec C #)
- champs publics (adore les POCO propres et lisibles, facilite également la tâche du compilateur C #)
- désactiver la génération de module
Ensuite, j'avais besoin d' interfaces C # et j'ai pensé qu'il était temps de créer mon propre truc et j'ai écrit un simple script T4 qui fait exactement ce dont j'avais besoin. Il comprend également Enums . Aucun repo requis, juste <100 lignes de T4.
Utilisation
Pas de bibliothèque, pas de NuGet, juste ce simple fichier T4 - utilisez "ajouter un élément" dans Visual Studio et choisissez n'importe quel modèle T4. Puis collez-le dans le fichier. Adaptez chaque ligne avec "ACME" dedans. Pour chaque classe C #, ajoutez une ligne
<#= Interface<Acme.Duck>() #>
L'ordre est important, tout type connu sera utilisé dans les interfaces suivantes. Si vous n'utilisez que des interfaces, l'extension de fichier peut être .d.ts , pour les énumérations , vous avez besoin d'un fichier .ts , car une variable est instanciée.
Personnalisation
Hackez le 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();
}
#>
Le niveau suivant du script consistera à créer l'interface de service à partir de la classe MVC JsonController.