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

TypeWriter扩展生成TS文件时自动导入外部类的问题排查

Fixing TypeWriter's Missing Import Statements Issue

Let's break down what's going wrong and how to fix it:

1. The Template Method Call Mistake

The biggest issue here is how you're referencing your Imports method in the template. TypeWriter uses $ for built-in variables (like $Name, $Properties), but custom methods require the @ symbol to invoke them.

Your current template uses $Imports, which TypeWriter doesn't recognize as a method call—it just treats it as a literal string. To fix this, replace $Imports with a call to your method, passing the current class and file context:

$Classes(*DTO)[ 
    @Imports(Class, File)
    export interface $Name { 
        $Properties[ // $LoudName $name: $Type;] 
    }
]
  • Class refers to the current class being processed in the $Classes loop
  • File refers to the current C# file being parsed (a global variable in TypeWriter templates)

2. Case Sensitivity Bug in the Imports Method

Looking at your Imports code, you're using lowercase name properties, but TypeWriter's model objects use PascalCase Name properties. This means your check for existing classes in the file will never match, leading to incorrect imports (or missing them entirely).

Here's the corrected method with proper PascalCase:

string Imports(Class c, File f) 
{ 
    IEnumerable<string> classesInFile = f.Classes.Select(p => p.Name); 
    IEnumerable<Type> externalTypes = c.Properties 
        .Select(p => p.Type) 
        .Where(t => ((!t.IsPrimitive || t.IsEnum) && !classesInFile.Contains(t.Name))) 
        .Select(t => t.IsGeneric ? t.TypeArguments.First() : t) 
        .Where(t => t.Name != c.Name && t.Name != "DbGeography") 
        .Distinct(); 

    return string.Join(Environment.NewLine, externalTypes.Select(t => $"import {{ {t.Name} }} from './misc';").Distinct()); 
}

Key fixes here:

  • Changed p.name to p.Name when getting class names from the file
  • Changed t.name to t.Name when checking if a type exists in the current file

3. Verify the Output

For your example C# class ADTO, this corrected code will generate:

import { BDTO } from './misc';
export interface ADTO { 
    // Id id: number;
    // EditionId editionId: number;
    // Mask mask: BDTO;
}

Additional Notes

  • Ensure your Imports method is defined in the same template file (or in a partial template included with @Include) so TypeWriter can access it
  • If you work with generic types that have multiple arguments, you may want to adjust the t.TypeArguments.First() line to handle all arguments, but this works for single-generic use cases like your example

内容的提问来源于stack exchange,提问作者j.her

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:24:20