CodeBlanks Logo Icon CodeBlanks

Question model

Design question, option, and answer types.

What is a question model?

In a quiz app, the question model is designed first. A question consists of text, options, and the index of the correct answer. In TypeScript you define this structure with an interface. This way all questions share the same shape and missing fields are caught at compile time.

interface Question {
  text: string;
  options: string[];
  correctIndex: number;
}

Answer and option types

Beside the question model, answer and option types are also defined. Options are a string[] array; the user's answer is the index of the chosen option, i.e. a number. This separation keeps each part of the model with a single responsibility.

type Answer = number;  // chosen option index
type Option = string;   // an option text

Practice Create a question object

Define a Soru interface: metin: string, siklar: string[], dogruIndex: number. Create a Soru object named s1 with text "TS nedir?", options ["dil", "renk", "araç"], and correct index 0. Print s1.metin with console.log.

Starter code

index.ts
// Soru interface tanımla
// s1 adında bir Soru nesnesi oluştur
// s1.metin yazdır

Sample solution

index.ts
interface Soru {
  metin: string;
  siklar: string[];
  dogruIndex: number;
}
const s1: Soru = {
  metin: "TS nedir?",
  siklar: ["dil", "renk", "araç"],
  dogruIndex: 0
};
console.log(s1.metin);

Expected output

TS nedir?

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What type should the dogruIndex field be in a Soru interface?

  • number Correct answer
  • string
  • boolean
  • string[]

Explanation: Since the index of the correct answer is a number, the dogruIndex field is defined as number.

2 Question interface keyword

Question
 ____ Soru {
  metin: string;
  siklar: string[];
  dogruIndex: number;
}
Answer
 interface Soru {
  metin: string;
  siklar: string[];
  dogruIndex: number;
}

Explanation: The interface keyword is used to define an object structure; type alias is an alternative but interface is more suitable for objects.

3 Question model parts

Term Meaning
metin Question text
siklar Options array
dogruIndex Correct answer index
Cevap Chosen option number

All lessons in Intermediate