I have successfully implemented TypeWriter to generate TypeScript classes from my C# models. The template I am currently using is shown below:
${
using Typewriter.Extensions.Types;
Template(Settings settings)
{
settings.IncludeProject("ProjectName.Api");
settings.OutputFilenameFactory = file =>
{
return file.Name.Replace("Dto.cs", ".ts");
};
}
string DtoName(Class t) { return t.Name.Replace("Dto", ""); }
string MapTypeName(Property p) { return MapTypeName(p.Type); }
string MapTypeName(Type t)
{
var typeArguments = t.TypeArguments.ToList();
if (typeArguments.Count == 1 && t.IsEnumerable)
{
return $"{MapTypeName(typeArguments[0])}[]";
}
if (typeArguments.Count == 2 && t.Name == $"KeyValuePair<{typeArguments[0]}, {typeArguments[1]}>")
{
return $"{{ key: {typeArguments[0]}; value: {typeArguments[1]}}}";
}
return t.Name.Replace("Dto", "");
}
}
module CompanyName.Models.Api {
$Classes(ProjectName.Api.Models.*Dto)[
export class $DtoName {
$Properties[
public $name: $MapTypeName = $Type[$Default];]
}]
}
I am looking to add a method conditionally for a specific type within this template. I initially tried the following approach:
module CompanyName.Models.Api {
$Classes(ProjectName.Api.Models.*Dto)[
export class $DtoName {
$Properties[
public $name: $MapTypeName = $Type[$Default];]
${
if ($name == "ADto")
{
// Code to be added conditionally goes here
}
}
}]
}
This syntax led to multiple Typewriter errors, including "unexpected token" and "invalid token". I then attempted a different variation:
module CompanyName.Models.Api {
$Classes(ProjectName.Api.Models.*Dto)[
export class $DtoName {
$Properties[
public $name: $MapTypeName = $Type[$Default];]
$if ($name == "ADto")
{
// Another attempt at conditional code insertion
}
}]
}
In this case, Typewriter included the entire $if { ... }
block in the output, which was not the desired outcome.
My question is whether I need to create a separate template specifically for this class or if there is a way to achieve this conditionally within the existing template. If it can be done, how should I go about it?