Typewriter: Import base class

In the previous article I explained how to handle inheritance in the generated Typescript files and, at the end, we saw that the compiler complained about not finding the base class name. We will fix this in this new article.

If you are new here and don’t know what Typewriter is or how to use it, then more details can be found din this article: Typewriter (C# to TypeScript)

To fix the issue described above , we need to create a new helper method in the C# part of the Typewriter template file (template.tst file) called ImportsList which returns the imports we need in order to get rid of the error. This method will be called before 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 ? $"?" : $"";

    string ImportsList(Class objClass)
        List<string> neededImports = new List<string>();

        if (objClass.BaseClass != null)
            neededImports.Add("import { " + objClass.BaseClass.Name + " } from './" + objClass.BaseClass.Name + "';");

        return String.Join("\n", neededImports.Distinct()); 
export interface $ClassNameWithExtends {$Properties[
    $Name$TypeNullableFormatted: $Type;]

And the generated Typescript file like this:

import { UserModel } from './UserModel';
export interface BloggerModel extends UserModel {
    BlogName: string;
    BlogUrl: string;

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

One Comment

  1. Stephen Denton said:

    Dude, these two articles were super-helpful. Thank you!

    December 5, 2020

Leave a Reply

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