Typewriter: Inheritance

In this article I will explain how to handle inheritance in generated classes using Typewriter.

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

Starting with the last example with UserModel class, let’s add a new class in the C# code, called BloggerModel. This new class extends the base class UserModel and it’s declared in a new file.

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

    public class BloggerModel: UserModel
        public string BlogName { get; set; }
        public string BlogUrl { get; set; }

After saving the new class, Typewriter will generate a new Typescript file called BloggerModel.ts with the following content:

export interface BloggerModel {
    BlogName: string;
    BlogUrl: string;

The new Typescript interface was added based on the last example and it does not know how to handle inheritance, Typewriter treats the new C# class as a as a normal class. 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 ClassNameWithExtends which checks if there is a base class. This method will be called after each class name.

The updated template looks like this:

    Template(Settings settings)
        settings.OutputExtension = ".ts";

    string ClassNameWithExtends(Class c) => c.Name + (c.BaseClass != null ? " extends " + c.BaseClass.Name : "");

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

And the new generated Typescript file like this:

export interface BloggerModel extends UserModel {
    BlogName: string;
    BlogUrl: string;

After generating the correct BloggerModel interface, Typescript complains about not finding name ‘UserModel’ and it shows a potential fix for the error. Do not import ‘UserModel’ as suggested, instead read the next article on how to generate the import list.

Now you know how to properly generate child classed using Typewriter :).

Be First to Comment

Leave a Reply

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