1

Working on getting some interfaces setup for my angular2 service using typescript. Running into an issue of configuration.

I'd like to be able to access my data like this myItem['chickens'] & get back the following object:

{
  name:"chicken",
  price:1000,
  names:["Harry", "Barry", "Larry"]
}

How do I write my interface the correct way so that I can get my data back as previously mentioned?

export interface StoreItem {
      itemName:{
        itemName: string;
        price: number;
        nameList: Array<string>;
      }
    }
1
  • Is it myItem: StoreItem? Commented Jan 2, 2017 at 18:02

1 Answer 1

6

Your StoreItems have string keys and typed values, so you could do:

interface StoreItem {
  [key: string]: {
    itemName: string;
    price: number;
    nameList: Array<string>;  // or string[]
  }
}

This would happily allow e.g.:

let myItem: StoreItem = {
  chickens: {
    name: 'chicken',
    price: 1000,
    names: ['Harry', 'Barry', 'Larry']
  }
};

And you can access that inner item either as myItem['chickens'] or simply myItem.chickens.

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.