Choosing to selectively trigger a function using TypeWriter

I have successfully implemented TypeWriter to generate TypeScript classes from my C# models. The template I am currently using is shown below:

${
    using Typewriter.Extensions.Types;

    Template(Settings settings)
    {
        settings.IncludeProject("ProjectName.Api");
        settings.OutputFilenameFactory = file => 
        {
            return file.Name.Replace("Dto.cs", ".ts");
        };
    }

    string DtoName(Class t) { return t.Name.Replace("Dto", ""); }
    string MapTypeName(Property p) { return MapTypeName(p.Type); }

    string MapTypeName(Type t)
    {
        var typeArguments = t.TypeArguments.ToList();

        if (typeArguments.Count == 1 && t.IsEnumerable)
        {
            return $"{MapTypeName(typeArguments[0])}[]";
        }

        if (typeArguments.Count == 2 && t.Name == $"KeyValuePair<{typeArguments[0]}, {typeArguments[1]}>")
        {
            return $"{{ key: {typeArguments[0]}; value: {typeArguments[1]}}}";
        }

        return t.Name.Replace("Dto", "");
    }
}

module CompanyName.Models.Api {
    $Classes(ProjectName.Api.Models.*Dto)[
    export class $DtoName {
        $Properties[
        public $name: $MapTypeName = $Type[$Default];]
    }]
}

I am looking to add a method conditionally for a specific type within this template. I initially tried the following approach:

module CompanyName.Models.Api {
    $Classes(ProjectName.Api.Models.*Dto)[
    export class $DtoName {
        $Properties[
        public $name: $MapTypeName = $Type[$Default];]

        ${
            if ($name == "ADto") 
            {
                // Code to be added conditionally goes here
            }
        }
    }]
}

This syntax led to multiple Typewriter errors, including "unexpected token" and "invalid token". I then attempted a different variation:

module CompanyName.Models.Api {
    $Classes(ProjectName.Api.Models.*Dto)[
    export class $DtoName {
        $Properties[
        public $name: $MapTypeName = $Type[$Default];]

        $if ($name == "ADto") 
        {
            // Another attempt at conditional code insertion
        }
    }]
}

In this case, Typewriter included the entire $if { ... } block in the output, which was not the desired outcome.

My question is whether I need to create a separate template specifically for this class or if there is a way to achieve this conditionally within the existing template. If it can be done, how should I go about it?

Answer №1

After some investigation, I was able to solve the issue with reference to a comment on a Github issue

To address this in the main body, simply insert this helpful function:

bool IsStatisticsClass(Class c)
{
    return c.Name == "ADto";
}

This creates a sort of enclosing structure (although the precise term eludes me). With $IsStatisticsClass[ ... ], we can conditionally include code. The template itself now appears as follows:

module CompanyName.Models.Api {
    $Classes(ProjectName.Api.Models.*Dto)[
    export class $DtoName {
        $Properties[
        public $name: $MapTypeName = $Type[$Default];]
        $IsStatisticsClass[            
        // The following code is generated for a single class:
        //    public getStatistic(appType: string, status: string): number {
        //        const retval = _.find(this.data, { appType: appType, status: status });
        //        return retval ? retval.count : 0;
        //    }]
    }]
}

To maintain consistency with my query, I have retained the TypeScript code that is produced but commented it out.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Vue 3 with TypeScript for enforcing type checking on single file components' props

In my exploration of Vuetify and other sources, I discovered that it is possible to incorporate type checking for props within the template tag. Let's consider a simple button component: <template> <div> <button>{{ label ...

Struggling to successfully pass React props.children

Currently, I am utilizing react in my project and I have encountered an error when passing props.children to the Header component. Despite passing React as the type, the following error message is displayed. I am unsure why this error is happening. e ...

What is the best method for retrieving an entity using a link table in Entity Framework?

I need some assistance with the join table, as I am struggling to recall the term for a table that contains only 2 foreign keys for 2 entities. Edit: Could it be called a link table? The database model appears as shown in this DB-Model entities. In the mo ...

What could be causing the discrepancy in JSON formatting between my data and the examples provided in High

Utilizing jQuery's $.GetJSON method results in the following output: {"Points":[{"X":1,"Y":6},{"X":2,"Y":5},{"X":3,"Y":1},{"X":4,"Y":5},{"X":5,"Y":5},{"X":6,"Y":10},{"X":7,"Y":4},{"X":8,"Y":1},{"X":9,"Y":9},{"X":10,"Y":2}]} Nevertheless, according t ...

What are some validation techniques for textboxes in ASP.NET using C#?

Recently adopted using c# in asp.net Curious about the most effective validation techniques for validating a textbox that should only contain numbers (including 1 decimal point). I've explored ajax but realized it relies on client support, so now I&a ...

Unpacking a JSON string into a custom object in C# without a predefined structure

Dealing with a JSON response from an API can be tricky when you only need certain data items. Is there a way to efficiently deserialize it into a C# object without the hassle of defining a class for every single element in the JSON result? Or do I have no ...

Having issues with an `else if` statement in Selenium not functioning correctly

Currently, I am facing an issue while trying to test a website using Selenium with C#. The website has 10 buttons displayed in random order, and my task is to verify the availability of each button. I attempted to address this by creating an else-if state ...

What are the benefits of utilizing a Mocking Framework?

Our current approach involves utilizing the DI model with Autofac as our IoC container. Lately, we have been exploring mocking frameworks such as MOQ and Rhino Mocks. However, we are finding it challenging to justify their use over simply creating mock im ...

An issue with MySql encountered in the MySqlDataReader

After executing the command, I have fetched data into a MySqlDataReader object named 'rdr'. I now have some information stored in my MySqlDataReader. How can I display this data on our website? I'm uncertain about how to utilize the MySqlD ...

Verify that each interface in an array includes all of its respective fields - Angular 8

I've recently created a collection of typed interfaces, each with optional fields. I'm wondering if there is an efficient method to verify that all interfaces in the array have their fields filled. Here's the interface I'm working wit ...

Troubleshooting error "is not assignable to type..." when simulating global fetch using TypeScript

I am encountering an issue with the "global.fetch" part and cannot seem to figure out why. Despite following the standard procedure, I am still facing this TS2322 error. I am seeking assistance to understand why this error is occurring. I am open to sugges ...

How does the process of calculating a CRC32 checksum differ between C# and Java?

I need to compute the CRC32 checksum for a string in C# and transmit it to an external application. They will verify it using Java on their end. However, there seems to be a discrepancy as my calculated checksum does not match theirs. For example, the C ...

Can the output type of a function be dynamically determined by using the function parameter name as the property in an interface?

I am attempting to dynamically assign the output of a function based on the name of the input parameter within an existing interface: interface MyInterface { typeA: string; typeB: boolean; typeC: string; typeD: number; ... } const myFunction: ( ...

Using React and Typescript: Passing functions as props to other components

In this setup, we have three main components: Toggle, ToggleMenu, and Wrapper. The Toggle component is designed to be universal and used for various functions. The Wrapper component, on the other hand, is meant to change the background color only when the ...

Error 0x8007007a encountered while loading a .NET assembly resulted in a System.IO.FileLoadException

We are encountering an issue with launching certain in-house .NET applications on Windows 10 Version 1607 machines. At times, starting an application is unsuccessful due to a failure in loading a dependent .NET assembly. The accompanying error message read ...

Error: TypeScript is flagging that you can only specify known properties in an object literal, and the property '...' does not exist in the type 'DeepPartial<Document>'

I've been working on building a basic controller API in NodeJS with TypeScript, but I'm encountering the error ts(2345) while trying to assign values to the model. This is my user model: import mongoose, {Schema} from 'mongoose' cons ...

Error: The variable _ is undefined when trying to use the .map() function on an array

While working on my project, I encountered a "ReferenceError: _ is not defined" when using the .map function in this code snippet: arr.map(async (elem) => { ... }); I couldn't find any explicit mention of "_" in my code. The error trace pointed me ...

The usage of $http.post in combination with TypeScript accessors

Currently, I am developing an AngularJS application (v1.3.15) using TypeScript 1.5 in Visual Studio 2013. I have encountered a challenge related to TypeScript object properties and JSON serialization while utilizing $http.post(). Although I consider myself ...

Utilizing AJAX to invoke the onget method with parameters in .NET Core

I attempted to invoke the onget method in .net core using an ajax call, but the method is being called without any parameters public void OnGet(string id,string refundReason ,int amount) { } I tried two different aj ...

What is the functionality of ngModel in the Angular Heroes Tour tutorial?

Hello everyone, this is my first post here. I have been diving into the Angular Tour of Heroes using Angular 6 and I think I understand how ngModel works, but there's one thing that puzzles me. How does it manage to update the data in my list when th ...