jburzynski / TypeGen

Single-class-per-file C# to TypeScript generator
MIT License
197 stars 56 forks source link

Add import path support for CustomTypeMappings #198

Open mike8161990 opened 7 months ago

mike8161990 commented 7 months ago

In my team's project, we prefer to map all DateTime and DateTimeOffset C# types to a Moment TypeScript type. Using this type requires an additional import from the moment package.

I found that I am able to do this for individual fields using a GenerationSpec:

public class DemoGenerationSpec : GenerationSpec
{
    public override void OnBeforeGeneration(OnBeforeGenerationArgs args)
    {
        this.AddInterface<UserDetailed>()
            .Member(t => nameof(t.CreatedOn))
            .Type("Moment", "moment");
    }
}

Or using an annotation:

public class UserDetailed
{
    [TsType("Moment", "moment")]
    public required DateTimeOffset CreatedOn { get; set; }

    // Trimmed for brevity
}

But I can't find a way to setup a universal type mapping rule which will affect all usage of a type. Does such a method exist?

Issue #175 seems to touch on this a bit noting that the CustomTypeMappings option could be changed from a IDictionary<string, string> to some kind of object allowing additional configuration. Maybe this would be a good use case for that restructuring?

janruo commented 4 months ago

+1 This would be very useful.

In the meantime, config can be used to map the type, and also inject its import to all generated files:

{
    "customTypeMappings": {
        "Some.Custom.Type": "SCT"
    },
    "fileHeading": "/** This is an auto-generated file */\r\n\r\nimport { SCT } from \"somewhere\";\r\n"
}

The downside is of course that it will be added to ALL generated files, even the ones that don't need it. But /* eslint-disable */ could also be injected to supress warnings.