Typelite:如何使用T4转换将可空C#类型设置为可空的Typescript类型?

RHA*_*HAD 5 reflection t4 system.reflection typescript typelite

我正在使用Typelite 9.5.0将我的C#类转换为Typescript接口.我想要一个可以为空的类型(例如Guid?)在Typescript中转换为可空类型.

目前我有这个C#类:

public class PersistentClassesReferences
{
public Guid? EmailMessageId { get; set; }
public Guid? FileMetaDataId { get; set; }
public Guid? IssueId { get; set; }
public Guid? ProjectId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

但是使用Typelite将其转换为此Typescript接口:

interface IPersistentClassesReferences {
    EmailMessageId : System.IGuid;
    FileMetaDataId : System.IGuid;
    IssueId : System.IGuid;
    ProjectId : System.IGuid;
}
Run Code Online (Sandbox Code Playgroud)

但是当我想从这个接口创建一个新的typescript变量时,编译器会在我没有设置所有属性时抱怨(某些值为null).

因此,我有一个模板,可以测试可空类型,如果有的话,添加一个?

var isNullabe = Nullable.GetUnderlyingType(tsprop.ClrProperty.PropertyType) != null;
if (isNullabe)
{
    return identifier.Name + "? ";
}
Run Code Online (Sandbox Code Playgroud)

这确实有效,但现在不行了(我想在升级到Typelite 9.5.0或其他一些nugetpackage更新之后).

我收到错误消息:

 Compiling transformation: 'System.Reflection.MemberInfo' does not contain a
 definition for 'PropertyType' and no extension method 'PropertyType' accepting
 a first argument of type 'System.Reflection.MemberInfo' could be found (are you
 missing a using directive or an assembly reference?)           
Run Code Online (Sandbox Code Playgroud)

如何在标识名中添加问号?

Dic*_*ink 9

您可以使用TsProperty属性创建它,例如,以下C#代码将生成一个可选属性:

[TsClass]
public class Person
{
    [TsProperty(IsOptional=true)]
    public string Name { get; set; }
    public List<Address> Addresses { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这将生成以下TypeScript定义

interface Person {
    Name?: string;
    Addresses: TypeScriptHTMLApp1.Address[];
}
Run Code Online (Sandbox Code Playgroud)

你可以在这里找到更多相关信息:docs

请参阅此处的代码:代码


Luk*_*brt 3

如果你想使用 TypeLite 格式化程序,这应该可以工作:

var propertyInfo = tsprop.ClrProperty as PropertyInfo;
var propertyType = propertyInfo != null ? propertyInfo.PropertyType : ((FieldInfo)tsprop.ClrProperty).FieldType;    
var isNullabe = Nullable.GetUnderlyingType(propertyType) != null;
if (isNullabe) {
    return identifier.Name + "? ";
}
Run Code Online (Sandbox Code Playgroud)