Classes 101
A class is a special type of JavaScript object which
is always created via a constructor. These classes
act a lot like objects, and have an inheritance structure
similar to languages such as Java/C#/Swift.
Here's an example class:
// An instance can be created via the new keyword, and
you can call methods and access properties from the
object.
class Vendor {
name: string;
constructor(name: string) {
this.name = name;
}
greet() {
return "Hello, welcome to " + this.name;
}
}
// You can subclass an object. Here's a food cart which
has a variety as well as a name:
const shop = new Vendor("Ye Olde Shop");
console.log(shop.greet());
// Because we indicated that there needs to be two arguments
to create a new FoodTruck, TypeScript will provide errors
when you only use one:
class FoodTruck extends Vendor {
cuisine: string;
constructor(name: string, cuisine: string) {
super(name);
this.cuisine = cuisine;
}
greet() {
return "Hi, welcome to food truck " + this.name + ". We serve " + this.cuisine + " food.";
}
}
// Correctly passing in two arguments will let you create a
new instance of the FoodTruck:
const nameOnlyTruck = new FoodTruck("Salome's Adobo");
const truck = new FoodTruck("Dave's Doritos", "junk");
console.log(truck.greet());