当对象的属性是字典并且其值是自定义类型时,我正在努力找出如何生成我的imports
行。
我的DTO / C#类定义如下。我的.tst文件中的Imports函数没有意识到它需要导入Status
类型,类似于它导入ProjectDTO
的方式。
是否可以获取.tst文件中字典值的类型?
C#文件
[TypeScript]
public class ActiveProjectsViewModel
{
public List<ProjectDTO> Projects { get; set; }
public Dictionary<int,Status> Statuses { get; set; }
public bool EditModeAvailable { get; set; }
}
.tst文件
${
string Imports(Class c)
{
var props = c.Properties.Where(p=>!p.Attributes.Any(a => String.Equals(a.name, "TypeScriptIgnore", StringComparison.OrdinalIgnoreCase)));
IEnumerable<Type> types = props
.Select(p => p.Type)
.Where(t => !t.IsPrimitive || t.IsEnum)
.Select(t => t.IsGeneric ? t.TypeArguments.First() : t)
.Where(t => !t.Attributes.Any(a => String.Equals(a.name, "TypeScriptIgnore", StringComparison.OrdinalIgnoreCase)))
.Distinct();
return string.Join(Environment.NewLine, types.Select(t => $"import {{ {t.Name} }} from './{t.Name}';").Distinct());
}
}
$Classes()[
$Imports
export class $Name {
$Properties($PropertyIsNotIgnored)[
public $name: $Type = $Type[$Default];]
$BaseClass[$Properties($PropertyIsNotIgnored)[
public $name: $Type = $Type[$Default];]]
}]
$Enums(*)[
export enum $Name {
$Values[
$Name = $Value][,]
}]
产生此文件:
import { ProjectDTO } from './ProjectDTO';
export class ActiveProjectsViewModel {
public projects: ProjectDTO[] = [];
public statuses: { [key: number]: Status; } = {};
public editModeAvailable: boolean = false;
}
答案 0 :(得分:1)
来自打字机的创建者,发布在这里:https://github.com/frhagn/Typewriter/issues/282 看起来字典中定义的类型可以使用以下方法派生。
SelectMany
行是添加的关键。
string Imports(Class c)
{
var props = c.Properties.Where(p => !p.Attributes.Any(a => String.Equals(a.name, "TypeScriptIgnore", StringComparison.OrdinalIgnoreCase)));
IEnumerable<Type> types = props
.Select(p => p.Type)
.SelectMany(t => t.IsGeneric ? t.TypeArguments : new[] { t } as IEnumerable<Type>)
.Where(t => !t.IsPrimitive || t.IsEnum)
.Where(t => !t.Attributes.Any(a => String.Equals(a.name, "TypeScriptIgnore", StringComparison.OrdinalIgnoreCase)))
.Distinct();
return string.Join(Environment.NewLine, types.Select(t => $"import {{ {t.Name} }} from './{t.Name}';").Distinct());
}