You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Typewriter工具:C#公共变量转TypeScript类的实现咨询

Handling C# Public Fields with Typewriter TypeScript Templates

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 with get/set accessors)
  • $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 like int → number, ICollection<T> → T[] by default)
  • $OriginalType: The raw C# type name if you need to implement custom type mappings

内容的提问来源于stack exchange,提问作者Anonymous Creator

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:18:57