Typewriter: Nullable types

In this article I will explain how to work with nullable types, more exactly how to tell Typewriter to handle nullable properties found in C# code.

More details about Typewriter and how to start using it can be found din this article: Typewriter (C# to TypeScript)

Starting with the first example with UserModel class, let’s add a new property in the C# code, a nullable property, called ‘Age’. C# UserModel class should look like this:

    public class UserModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public int? Age { get; set; }
    }

After saving this file, the generated Typescript file should contain a new property named “Age”:

export interface UserModel {
    Id: number;
    Name: string;
    Email: string;
    Age: number;
}

The new property was added based on the initial template and it does not know how to handle nullable types, Typewriter treats nullable properties as a normal properties. If we want to change this then the template needs to be updated. Therefor we create a new helper method in the C# part of the template (template.tst file), called TypeNullableFormatted which appends a ? next to any type that is nullable. This method will be called after each property name.

The updated template looks like this:

${
    Template(Settings settings)
    {
        settings.IncludeCurrentProject();
        settings.OutputExtension = ".ts";
    }

    // append a ? next to any type that is nullable
    string TypeNullableFormatted(Property property) => property.Type.IsNullable ? $"?" : $"";
}
$Classes(*Model)[
export interface $Name {$Properties[
    $Name$TypeNullableFormatted: $Type;]
}]

And the new generated Typescript file ( Typescript treats “Age” property as optional ) like this:

export interface UserModel {
    Id: number;
    Name: string;
    Email: string;
    Age?: number;
}

 

4 Comments

  1. Aurélien JOLY said:

    Here is the first time in all of your tutorials that you introduce an extension method that will use a scope (property scope) by injecting a Property it in the method. It would help understanding to mention this. Your TypeNullableFormatted method cannot be used outside a $Properties()[] loop đŸ˜‰

    November 7, 2019
    Reply
    • selfclosingbug said:

      If I don’t edit this soon I will try to explain better on my next Typewriter post đŸ™‚
      Thank you

      January 24, 2020
      Reply
  2. Elsa said:

    Thank you, sir!

    December 11, 2019
    Reply
    • selfclosingbug said:

      đŸ˜€

      January 24, 2020
      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *