In this task, we will create a simple counter app using TypeScript. The app will have the following features:
Unlike previous projects, where we used index.html
to create the layout, we will use TypeScript to create the layout.
Open the src/main.ts
file and add the following code:
In the above code, we have created a simple layout with three buttons: reset
, decrement
, and increment
. We have also added a div
element to display the counter value.
We are directly setting the innerHTML
of the app
element. This HTML string will be parsed and rendered by the browser. However, this is not a recommended approach as it can lead to issues such as inadvertently missing closing tags, forgetting to close quotes, etc. A better approach is to use the DOM API to create elements and append them to the app
element.
Notice that we have used !
after app
to tell TypeScript that app
will never be null
. This is because we are sure that the element with the id app
will always be present in the DOM. Alternatively, you can use the following code to check if the element is present:
First, add the following import statement at top of the src/main.ts
file:
Next, update src/styles.css
and add the following CSS code:
In the above code, we have added some basic styling to the counter app. The background color of the HTML is set to black, the text color is light gray, and the font-family is set to Courier New
. The counter is displayed in a large font size with a light gray color. The buttons are styled with a circular shape, border, and hover effects.
Open the terminal and run the following command to start the development server:
The app should now be running on http://localhost:5173
with the counter layout and styling.
Now, let’s implement the counter logic. We will create a variable count
to store the counter value and update the counter value when the buttons are clicked.
In the above code, we have added event listeners to the increment
, decrement
, and reset
buttons to update the counter value and call the updateCounter
function to display the updated value.
Try clicking the buttons to see the counter value change.
In this task, we created a simple counter app using TypeScript. We set up the layout, added styling, and implemented the counter logic. You can further enhance the app by adding additional features such as limiting the counter value, changing the color based on the value, etc.
It is important to notice the pattern of updating the UI based on the state changes. This pattern is commonly used in web development to create interactive applications. We have to manage the state of the application and update the UI accordingly. In the next task, we will use React to create a similar counter app and see how React simplifies the process of managing state and updating the UI.