Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typelite: how to set nullable C# types to nullable Typescript types with T4 transform?

I'm using Typelite 9.5.0 to convert my C# classes to Typescript interfaces. I want that a nullable type in (e.g. Guid?) is converted to a nullable type in Typescript.

Currently I have this C# class:

public class PersistentClassesReferences
{
public Guid? EmailMessageId { get; set; }
public Guid? FileMetaDataId { get; set; }
public Guid? IssueId { get; set; }
public Guid? ProjectId { get; set; }
}

But that is converted with Typelite to this Typescript interface:

interface IPersistentClassesReferences {
    EmailMessageId : System.IGuid;
    FileMetaDataId : System.IGuid;
    IssueId : System.IGuid;
    ProjectId : System.IGuid;
}

But when I want to create a new typescript variable from this interface, the compiler complains when I don't have all the properties set (null of some value).

Therefore I had a template in place that test for nullable type, and if so adds an ?

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

This did work, but not anymore (I think after the upgrade to Typelite 9.5.0 or some other nugetpackage update).

I get the error message:

 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?)           

How can I add a question mark to the identifiername?

like image 478
RHAD Avatar asked Sep 26 '14 06:09

RHAD


1 Answers

You can create it with the TsProperty Attribute, for example the following C# code will result in an optional property:

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

This will generate the following TypeScript definition

interface Person {
    Name?: string;
    Addresses: TypeScriptHTMLApp1.Address[];
}

You can find more about this here: docs

See the code where it does it here: code

like image 160
Dick van den Brink Avatar answered Sep 28 '22 06:09

Dick van den Brink