M
M
MarEeeeeee2021-05-15 14:31:28
typescript
MarEeeeeee, 2021-05-15 14:31:28

How to correctly implement an array of objects in TypeScript?

Hello.
Before the main question, I would like to ask a side question.
The purpose of the task is to make a quiz. That is, there is a question and n-th number of answer options.
To store all questions and quizzes, I'm going to use something like this

const questions: {question?: string, option1?: string, option2?: string, option3?:string, option4?: string}[] = [
    {
        question : "text of question 1",
        option1: "opt1",
        option2: "opt2",
        option3: "opt3",
        option4: "opt4"
    },
    {
        question : "text of question 2",
        option1: "opt1",
        option2: "opt2",
        option3: "opt3",
        option4: "opt4",
    },{},{},{},{},{},{},{},{}
];

there are doubts about this. Perhaps it's better to do something differently?

Other than that, I don't understand how to initialize this array in TypeScript. Because the number of properties for objects can be different.

Tell me pliz

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Michael, 2021-05-15
@MarEeeeeee

interface Question {
  question: string;
  option1: string;
  option2: string
  ...
}
const questions: Question[] = [...]

although option${index} is a crutch, discover arrays

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question