0

I got data from an external interface and the data structure is kind of strange. I am trying to build a typescript interface for it.

{
   "userIds": {
        "431a87306b4bcba4": {
          "user_name": "JonDoe",
          "first_name": "Jon",
          "last_name": "Doe",
          "name": "JonDoe"
        },
        "141a87306b4bcba4": {
          "user_name": "JonDoe2",
          "first_name": "Jon2",
          "last_name": "Doe2",
          "name": "JonDoe2"
        }
      }
}

My idea was this, but I think it is not correct.

export class Data {
  userIds: Dic;
}

interface Dic {
  [key: string]: User
}

export class User {
  user_name: string;
  first_name: string;
  last_name: string;
  name: string;
}

Would be glad if one of you type experts could help me - thanks :)

1 Answer 1

1

You could make use of Record<string, User>.

export interface Data {
  userIds: Record<string, User>;
}

export interface User {
  user_name: string;
  first_name: string;
  last_name: string;
  name: string;
}

const data: Data = {
  userIds: {
    "431a87306b4bcba4": {
      user_name: "JonDoe",
      first_name: "Jon",
      last_name: "Doe",
      name: "JonDoe",
    },
    "141a87306b4bcba4": {
      user_name: "JonDoe2",
      first_name: "Jon2",
      last_name: "Doe2",
      name: "JonDoe2",
    },
  },
};

Please note: What you have posted here is not valid JSON and not a valid JS object so I have added {} around that to make it a valid object.

"userIds": {
        "431a87306b4bcba4": {
          "user_name": "JonDoe",
          "first_name": "Jon",
          "last_name": "Doe",
          "name": "JonDoe"
        },
        "141a87306b4bcba4": {
          "user_name": "JonDoe2",
          "first_name": "Jon2",
          "last_name": "Doe2",
          "name": "JonDoe2"
        }
      }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.