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

使用Typewriter将单个C#文件中的多类拆分至独立TS文件

解决Typewriter从单个C#文件生成多个TypeScript文件的问题

没问题!要实现从单个包含多个类的C#文件生成独立的TypeScript文件,我们只需要调整自定义特性的构造函数,再配合Typewriter的模板逻辑就能轻松搞定。

步骤1:更新ExportToTypescript特性定义

首先确保你的自定义特性能接收输出文件名作为参数,这样每个类可以指定自己的目标.ts文件:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class ExportToTypescriptAttribute : Attribute
{
    // 存储目标输出文件名
    public string OutputFileName { get; }

    // 构造函数接收输出文件名参数
    public ExportToTypescriptAttribute(string outputFileName)
    {
        OutputFileName = outputFileName;
    }
}

你的FooBar.cs文件可以保持现有写法,注意补全属性的访问修饰符(比如public),否则Typewriter可能无法正常识别类成员:

[ExportToTypescript("Foo.ts")]
public class Foo { public string prop1 { get; set; } public string prop2 { get; set; } }

[ExportToTypescript("Bar.ts")]
public class Bar { public string prop1 { get; set; } public string prop2 { get; set; } }

步骤2:编写Typewriter模板

创建一个Typewriter模板文件(比如命名为MultiFileExport.tst),利用模板的WriteToFile方法,根据每个类的特性参数输出到对应的文件:

${
    // 筛选出所有带有ExportToTypescript特性的类
    var targetTypes = Types.Where(t => t.Attributes.Any(a => a.Name == "ExportToTypescript"));
    
    foreach(var type in targetTypes)
    {
        // 从特性中提取目标输出文件名
        var outputFileName = type.Attributes
            .First(a => a.Name == "ExportToTypescript")
            .Arguments.First().Value;
        
        // 将当前类生成的TypeScript代码写入指定文件
        WriteToFile(outputFileName, $@"
export interface {type.Name} {{
    {string.Join("\n    ", type.Properties.Select(p => $"{p.Name}: {p.Type.Name.ToLower()};"))}
}}
");
    }
}

实现效果

当Typewriter运行这个模板时,会自动完成以下操作:

  • 识别FooBar.cs里带有ExportToTypescript特性的两个类
  • 分别生成Foo.ts和Bar.ts独立文件
  • 每个.ts文件只包含对应类的TypeScript接口,比如Foo.ts的内容如下:
export interface Foo {
    prop1: string;
    prop2: string;
}

内容的提问来源于stack exchange,提问作者Richard Watts

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:26:56