public
Last active

Generate Typescript interface (run this razor file within web application with refs to your project with the models) Stolen from http://typescript.codeplex.com/discussions/406685 and slightly modified

  • Download Gist
generateTypescriptInterface.cshtml
C#
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 70 71 72 73
@functions{
public List<Type> Types = new List<Type>()
{
typeof(MyDomain.Common.Models.SomeTypeA),
typeof(MyDomain.Common.Models.SomeTypeB)
};
string getTypesScriptType(string propertyType)
{
switch (propertyType)
{
case "System.String":
return "string";
 
case "System.Int32":
return "number";
 
case "System.Boolean":
return "bool";
case "System.Nullable`1[System.Boolean]":
return "bool";
 
case "System.Nullable`1[System.Int32]":
return "number";
default:
break;
}
return null;
}
}
 
 
<pre>
 
@foreach (var t in Types)
{
<text>interface</text> @t.Name @("{")
<text>
</text> // force a line break
foreach (var p in t.GetProperties())
{
var typeString = getTypesScriptType(p.PropertyType.ToString());
if (typeString == null)
{
<text>//@p.Name: of type @p.PropertyType does not have a corresponding typescript type mapping yet</text>
}
else
{
if (p.PropertyType.ToString().Contains("Nullable"))
{
@(string.Format("{0}?: {1}; // {2}", p.Name, typeString, p.PropertyType))
}
else
{
@(string.Format("{0}: {1}; // {2}", p.Name, typeString, p.PropertyType))
}
<text>
</text> // force a line break
}
 
}
@("}")<text>// @t.Name</text>
<text>
</text> // force a line break
}
 
</pre>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.