typescript - Làm thế nào để tôi nhập các kiểu được định nghĩa trong một từ điển C#?
Tôi đang gặp khó khăn trong việc tìm cách tạo dòng imports của mình khi thuộc tính trên một đối tượng là một từ điển và giá trị của nó là một kiểu tùy chỉnh.
Lớp DTO/C# của tôi được định nghĩa bên dưới. Hàm Imports trong tệp .tst của tôi không nhận ra rằng nó cần nhập kiểu Status, tương tự như cách nó đã nhập ProjectDTO.
Có cách nào để lấy kiểu của các giá trị trong từ điển trong tệp .tst không?
Tập tin C#
[TypeScript]
public class ActiveProjectsViewModel
{
public List<ProjectDTO> Projects { get; set; }
public Dictionary<int,Status> Statuses { get; set; }
public bool EditModeAvailable { get; set; }
}
tệp .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][,]
}]
Tạo ra tệp này:
import { ProjectDTO } from './ProjectDTO';
export class ActiveProjectsViewModel {
public projects: ProjectDTO[] = [];
public statuses: { [key: number]: Status; } = {};
public editModeAvailable: boolean = false;
}
Câu trả lời #1
Từ nhà tạo ra Typewriter đăng ở đây: https://github.com/frhagn/Typewriter/issues/282 có vẻ như loại được định nghĩa trong từ điển có thể được suy ra bằng cách tiếp cận dưới đây.
Dòng SelectMany là dòng quan trọng đã được thêm vào.
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());
}
