Skip to content

Instantly share code, notes, and snippets.

@joeriks
Last active December 11, 2015 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeriks/4604497 to your computer and use it in GitHub Desktop.
Save joeriks/4604497 to your computer and use it in GitHub Desktop.
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
@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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment