In: Computer Science
Typescript can be mentioned as typed Javascript because it is a strongly typed fully object oriented language which compiles to plain javascript. Typescript cannot be run on a browser directly. It has to be compiled to javascript. Files written in typesript have .ts file extension
One of the ways to compile a typescript file is using the typescript npm package. The following command installs typescript in the machine
npm i -g typescript
After writing a typescript file, we need to compile it so that the corresponding javascript file (with .js extension) can be generated and used in our html file. The following command compile .ts file to corresponding .js file
tsc filename.ts
In our given problem we will be writing a grocery.ts file and do the following command in the terminal
tsc grocery.ts
SOLUTION
In our given problem we have been asked to create a class, few objects of the class and display it the html page. Which can be done as follows
grocery.ts
// create a class
class Grocery {
// declare properties and corresponding data type
name: string;
quantity: number;
price: number;
// add a constructor
constructor(n: string, q: number, p: number){
this.name = n;
this.quantity = q;
this.price = p;
}
}
// create a list of grocery items
// new keyword is used to inititalise objects
let list_of_items = [
new Grocery("milk", 3, 10),
new Grocery("bread", 6, 25),
new Grocery("egg", 11, 10)
]
// access the html element with id app
const ele = document.getElementById("app");
// create a <p> element for each item in the grocery list and
// append it to the html page
list_of_items.forEach(e => {
const p = document.createElement("p");
p.textContent = `${e.name} ${e.quantity} -> $${e.price}`;
ele.appendChild(p);
});
It is important to compile the above file into a .js file before it can be used in our html page. It can be done with the command given above i.e., tsc grocery.ts
groceries.html
<!DOCTYPE html>
<html lang="en">
<head><title>Groceries list</title></head>
<body>
<h3>List of groceries purchased</h3>
<!-- element where the list will be appended -->
<div id="app"></div>
<!-- we refer to the compiled js file here -->
<script src="grocery.js"></script>
</body>
</html>
*****OUTPUT*****