Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typescript compilation fails for DTO with Dictionary<Enum, string> property #1524

Closed
Shaddix opened this issue May 30, 2022 · 1 comment
Closed

Comments

@Shaddix
Copy link
Contributor

Shaddix commented May 30, 2022

The following property in DTO:

public Dictionary<DateTimeKind, string> EnumDictionary { get; set; }

Generates the following piece of code in toJSON method:

        if (this.enumDictionary) {
            data["enumDictionary"] = {};
            for (let key in this.enumDictionary) {
                if (this.enumDictionary.hasOwnProperty(key))
                    (<any>data["enumDictionary"])[key] = this.enumDictionary[key];
            }
        }

Typescript complains:

error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ readonly Unspecified?: string | undefined; readonly Utc?: string | undefined; readonly Local?: string | undefined; }'.
  No index signature with a parameter of type 'string' was found on type '{ readonly Unspecified?: string | undefined; readonly Utc?: string | undefined; readonly Local?: string | undefined; }'.

2217                     (<any>data["enumDictionary"])[key] = this.enumDictionary[key];
                                                              ~~~~~~~~~~~~~~~~~~~~~~~~

Apparantely, typescript assumes key is of type string.

@Shaddix
Copy link
Contributor Author

Shaddix commented May 30, 2022

I guess the easiest fix is to change

(<any>data["enumDictionary"])[key] = this.enumDictionary[key];

into

(<any>data["enumDictionary"])[key] = (<any>this.enumDictionary)[key];

But if you prefer, it could also be fixed by properly typing the key:

data["enumDictionary"] = {};
let key: keyof typeof this.enumDictionary;
for (key in this.enumDictionary) {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant