我正在使用 Typelite 9.5.0 将我的 C# 类转换为 Typescript 接口(interface)。我希望将可空类型(例如 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; }
}
但是这是用 Typelite 转换成这个 Typescript 接口(interface)的:
interface IPersistentClassesReferences {
EmailMessageId : System.IGuid;
FileMetaDataId : System.IGuid;
IssueId : System.IGuid;
ProjectId : System.IGuid;
}
但是当我想从这个接口(interface)创建一个新的 typescript 变量时,编译器会在我没有设置所有属性(某些值为空)时提示。
因此我有一个模板来测试可空类型,如果是的话添加一个?
var isNullabe = Nullable.GetUnderlyingType(tsprop.ClrProperty.PropertyType) != null;
if (isNullabe)
{
return identifier.Name + "? ";
}
这确实有效,但不再有效(我认为在升级到 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?)
如何在标识符名称中添加问号?
最佳答案
您可以使用 TsProperty 属性创建它,例如,以下 C# 代码将产生一个可选属性:
[TsClass]
public class Person
{
[TsProperty(IsOptional=true)]
public string Name { get; set; }
public List<Address> Addresses { get; set; }
}
这将生成以下 TypeScript 定义
interface Person {
Name?: string;
Addresses: TypeScriptHTMLApp1.Address[];
}
您可以在这里找到更多相关信息:docs
在此处查看代码:code
关于reflection - Typelite:如何使用 T4 转换将可为空的 C# 类型设置为可为空的 Typescript 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26053460/