2

To hopefully simplify my question, I have broken it down like so:

What I do understand

If this is my object:

{ 
     things: [{
         'text': 'version'
         'short': 'v',
         'order': 1,
         'id': 'A'
     },{
         'text': 'update'
         'short': 'u',
         'order': 2,
         'id': 'B'
     }]
}

...then this is my type class:

 export class Thing {
     text: string;
     short: string;
     order: number;
     id: string;
 }

What I do not understand

If this is my data:

 { things: {
         'A': {
             'text': 'version'
             'short': 'v',
             'order': 1,
             'id': 'A'
         },
         'B': {
             'text': 'update'
             'short': 'u'
             'order': 2
             'id': 'B'
         }
     }
 }

...then the type class is...?

I have tried some really creative, ineffective tries to get this to work to no avail. I'm also hoping I can make sense of what to do with this non-array array (no square-brackets). Apologies if this is a duplicate.

1
  • 1
    JSON is a textual notation for data exchange. (More here.) If you're dealing with JavaScript source code, and not dealing with a string, you're not dealing with JSON. Commented Oct 11, 2018 at 14:03

1 Answer 1

4

In that second situation, your things type would be an index type like this:

interface ThingHolder {
    [key: string]: Thing;
}

That says that the keys are strings and the values are Things.

The interface for data would be something that has a things property of that type:

interface AppropriateNameHere {
  things: ThingHolder;
}

So then, the compiler is happy with this:

const data : AppropriateNameHere = {
  things: {
    'A': {
      'text': 'version',
      'short': 'v',
      'order': 1,
      'id': 'A'
    },
    'B': {
      'text': 'update',
      'short': 'u',
      'order': 2,
      'id': 'B'
    }
  }
};

Live Example on the TypeScript playground.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent! Thanks very much!

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.