Typewriter工具:C#公共变量转TypeScript类的实现咨询
Got it, I've run into this exact scenario before with Typewriter—since the default $Properties directive only targets C# properties (the ones with get; set;), you need to use the $Fields directive to pick up public class fields instead.
Let me break this down for you:
First, let's clarify the key directive difference in Typewriter:
$Properties: Iterates over C# properties (members withget/setaccessors)$Fields: Iterates over C# fields (public variables without accessors)
Option 1: Template for Only Public Fields
If you want to generate TypeScript models specifically for C# classes with public fields, modify your template to swap $Properties with $Fields:
module App { $Classes(*Model)[ export class $Name { $Fields[ public $name: $Type;] } ] }
For a C# class like this:
public class ProductModel { public int ProductId; public string ProductName; public decimal Price; }
This will generate the expected TypeScript model:
module App { export class ProductModel { public ProductId: number; public ProductName: string; public Price: number; } }
Option 2: Template for Both Properties and Fields
If you need to handle a mix of properties (with get/set) and public fields in the same template, you can combine both directives to cover all members:
module App { $Classes(*Model)[ export class $Name { $Properties[ public $name: $Type;] $Fields[ public $name: $Type;] } ] }
This way, any C# class with a mix of property and field members will have all of them included in the generated TypeScript model.
Quick Notes on Field Variables
Just like with $Properties, $Fields gives you access to handy variables for customization:
$Name: The exact name of the C# field (preserves casing, which aligns well with TypeScript conventions)$Type: The auto-mapped TypeScript type (Typewriter handles common conversions likeint→number,ICollection<T>→T[]by default)$OriginalType: The raw C# type name if you need to implement custom type mappings
内容的提问来源于stack exchange,提问作者Anonymous Creator

