A quiz app built with TypeScript provides an interactive way to test knowledge while using TypeScript’s strong typing for better code quality. By implementing features like multiple-choice questions, score tracking, and timers, we can create a robust and engaging quiz experience for users.
What We’re Going to Create
We are going to build a Quiz App including Components.
A Question component
An options component containing the options for all the questions
A time Component to show the time
A Result component containing the result of the current quiz and a restart button to restart the quiz.
This HTML code structures the layout for a quiz application, including placeholders for questions, options, a timer, and score display and the CSS improves the User interaction for the game.
In this example
The quiz container (.qz) is styled with a clean, centered layout, using a modern design with a white background, rounded corners, and shadows for a polished look.
The question (.q), options (.opts), and result (.rs) sections are structured for easy JavaScript manipulation, allowing dynamic updates to display questions and track scores.
A timer (#t), answer options (.opt), and a restart button (.rst-btn) enhance interactivity, with smooth transitions and hover effects for a better user experience.
Quiz App – TypeScript Logic
This TypeScript code is designed to create an interactive quiz application that displays questions with multiple-choice options, tracks the score, and manages a countdown timer. It dynamically loads questions, checks answers, and provides a result at the end.
In this example
Questions, options, and answers are stored in an array of objects, ensuring type safety with the QuizData interface.
The loadQuestion function updates the UI with new questions and options, while checkAnswer validates selections and tracks the score.
The startTimer function runs a countdown, ending the quiz when time expires. The restartBtn resets the quiz, allowing users to start over.
The displayResult function shows the final score and hides the question UI when the quiz ends.
Event listeners handle user interactions, ensuring seamless navigation through questions.
Convert to JavaScript File
Now You need to convert the TypeScript file into JavaScript to render by browser. Use one of the following command-
npx tsc intro.ts tsc intro.ts
The command tsc intro.ts compiles the intro.js TypeScript file into a intro.js JavaScript file.
It places the output in the same directory as the input file by default.