This is my second step with TypeScript. This time I will declare interfaces and classes. My idea is to create a simple class and interface and use it like a “Hello world” example.
The first step is to declare an interface:
interface Pet {
name: string;
age: number;
color: string;
}
We use the keyword “interface”, followed by the interface’s name. After that in curly brackets, we describe properties. To use the interface declare a variable in a function or somewhere else with the interface’s name as the type. We can use the interface as a parameter of a function or use a class to implement it. First, we will start with an example with a function:
function showPetInfo(animal: Pet)
{
return animal.name +" ("+animal.color+ ") with age "+animal.age;
}
And its usage:
let myPet = { name: "Reks", age:2, color:"black" };
console.log (showPetInfo(myPet));
The function returns a custom string with properties part of the interface and the next row shows it. The next example is to declare a class. The class will implement the interface from the example above.
class Dog implements Pet
{
name: string;
age: number;
color: string;
constructor(name: string,age: number,color:string)
{
this.name = name;
this.color = color;
this.age = age;
}
public showInfo()
{
console.log (showPetInfo(this));
}
}
In the code above, we see that after implementation we need to declare properties that are the same as the properties in the interface. The constructor sets values to the class and we can use it. In this example, we can use functions with the class as a parameter.
let myDog = new Dog("Reks",3,"black");
console.log (showPetInfo(myDog));
myDog.showInfo();
Leave A Comment