If you are completely new to typescript, then i suggest you go through earlier post about Typescript basic syntax example, that will help you to understand this tutorial better.
Here we see Typescript class example, learn how to create typescript object, instance of typescript class!
In this tutorial we learn how to create typescript class and its properties, methods in it. If you are familiar with c#, JavaScript, Php etc. You may find much similarity in syntax.
TypeScript is an open-source, object oriented programming language developed by Microsoft.
export class StudentComponent
{
studentId: number=0;
title: string = "Create";
errorMessage: any;
fullname: string="";
address: string = "";
isActive: boolean = true;
}
Now we see how to write constructor in TypeScript class, it starts with constructor keyword, we can have any number of parameters in constructor defination
export class StudentComponent
{
constructor(private router: Router,
private formBuilder: FormBuilder, private _http: Http, @Inject('BASE_URL') baseUrl: string)
{
this.myAppUrl = baseUrl;
}
}
OnInit Event implementation in TypeScript Class
We can initialize some property value when the class instance is created, and in typescript there is special
way to write the on initialized event using implements OnInit .
export class CreateStudentComponent implements OnInit {
ngOnInit() {
// here we can initialize property values
}
}
Inheritance example in TypeScript Class
Here we learn how to use inheritance feature in TypeScript class
class TeamMember {
name: string;
constructor(name: string) {
this.name = name;
}
}
This is how you can inherit the above class to a new class
class Student extends TeamMember {
memberId: number;
constructor(empcode: number, name: string) {
super(name);
this.memberId = empcode;
}
displayName(): void {
console.log("Name = " + this.name +
", Member Id = " + this.memberId);
}
}
Using super we are calling the constructor of base class
You may be interested to read following posts: