0

I need to declare several variables of the same type (interface) at the time that I declare an array.

I am using it in an Angular 8 project, obviously using typescript.

I have this now:


export class GridComponent {

  pizza0: Pizza;
  pizza1: Pizza;
  pizza2: Pizza;
  pizza3: Pizza;
  pizza4: Pizza;
  pizza5: Pizza;

  constructor() {}

}

interface Pizza {
 name: string;
 ingredients: number;
 price: string;
}

And I want something like:


PizzaList: Array<Pizza> = new Array<Pizza>(pizza0, pizza1, pizza2, pizza3, pizza4, pizza5);


interface Pizza {
 name: string;
 ingredients: number;
 price: string;
}

And that each of the variables that I define within the array are declared initially

2
  • What do you mean declared? Initialized as a pizza object? In that case, use a class instead of and interface. Commented Jun 17, 2019 at 14:22
  • It is an interface, and I am doing this within an Angular component Commented Jun 17, 2019 at 15:42

2 Answers 2

1

I assume you want pizzaList to be an array of Pizza objects. You can create that as follows:

const pizzaList: Array<Pizza> = [
    { name: 'Margherita', ingredients: 1337, price: 9.99 },
    { name: 'Quattro stagioni', ingredients: 1337, price: 9.99 }
];

If you just want to declare it as "An array of pizzas, with length 6", that is not possible. You cannot declare it as a fixed length array of Pizza objects, you can only declare it as an array of pizza objects without specifying the length.

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

2 Comments

Yes but, I don't want to initialize them, just declare. So I don't want to put all the properties of each object. I just want to say like "I have an array of 6 pizzas with the type pizza": PizzaList: Array<Pizza> = new Array<Pizza>(pizza0, pizza1, pizza2, pizza3, pizza4, pizza5);
That is not possible. You cannot define an array with a statically typed length. You can only say: PizzaList: Array<Pizza> to define it as an array of Pizza objects. I have updated my answer.
0

You can do it without initializing the array with new Array<T>.

If your values are predefined then you can do it like:

PizzaList: Array<Pizza> = [pizza0, pizza1, pizza2, pizza3, pizza4, pizza5];

Or you can create them like:

PizzaList: Array<Pizza> = [
    new Pizza(/*args*/),
    new Pizza(/*args*/),
    new Pizza(/*args*/)
];

1 Comment

I cannot create like this because Pizza its an Interface, not a class

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.