Typelite: Why is Dictionary mapped to KeyValuePair and not to any or [index:string]:any

前端 未结 3 1244
遥遥无期
遥遥无期 2021-02-14 21:16

I have a class,

public class Instance : IResource
{
   public Dictionary Value { get; set; }

and it is mapped to

<
3条回答
  •  春和景丽
    2021-02-14 21:56

    Here's a more generalized (and updated) solution that builds off of Markus Jarderot's answer:

    static void RegisterDictionaryMemberFormatter(this TsGenerator tsGenerator)
    {
        tsGenerator.SetMemberTypeFormatter((tsProperty, memberTypeName) => {
            var dictionaryInterface =
                tsProperty.PropertyType.Type.GetInterface(typeof(IDictionary<,>).Name) ??
                tsProperty.PropertyType.Type.GetInterface(typeof(IDictionary).Name);
    
            if (dictionaryInterface != null)
            {
                return tsGenerator.GetFullyQualifiedTypeName(new TsClass(dictionaryInterface));
            }
            else
            {
                return tsGenerator.DefaultMemberTypeFormatter(tsProperty, memberTypeName);
            }
        });
    }
    
    // and if you like the fluent syntax...
    static TypeScriptFluent WithDictionaryMemberFormatter(this TypeScriptFluent typeScriptFluent)
    {
        typeScriptFluent.ScriptGenerator.RegisterDictionaryMemberFormatter();
        return typeScriptFluent;
    }
    

    Use it like this:

    var ts = TypeLite.TypeScript.Definitions().For(typeof(SomeClass).Assembly);
    ts.ScriptGenerator.RegisterDictionaryMemberFormatter();
    
    // alternatively with fluent syntax:
    
    var ts = TypeLite.TypeScript.Definitions()
        .For(typeof(SomeClass).Assembly)
        .WithDictionaryMemberFormatter();
    

    N.B. this only fixes type signatures of properties (or fields) that have dictionary types. Also definitions for IDictionary are not automatically emitted, you'd have to add them manually:

    declare module System.Collections.Generic {
        interface IDictionary {
            [key: string]: TValue;
        }
    }
    declare module System.Collections {
        interface IDictionary {
            [key: string]: any;
        }
    }
    

提交回复
热议问题