Skip to content

Instantly share code, notes, and snippets.

@luismisanchez
Created January 15, 2021 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luismisanchez/4b399c43449ab652ba4d7a8c13941b61 to your computer and use it in GitHub Desktop.
Save luismisanchez/4b399c43449ab652ba4d7a8c13941b61 to your computer and use it in GitHub Desktop.
Typescript Classes
// Classes allow us to create 'blueprints' for objects
// In Angular 2 we use classes a lot. For example to create Components, Services, Directives, Pipes, ...
// How to create a class
class Car {
engineName: string;
gears: number;
private speed: number;
constructor(speed: number) {
this.speed = speed || 0;
}
accelerate(): void {
this.speed++;
}
throttle():void {
this.speed--;
}
getSpeed():void {
console.log(this.speed);
}
static numberOfWheels(): number {
return 4;
}
}
// Instantiate (create) an object from a class
let car = new Car(5);
car.accelerate();
car.getSpeed();
console.log(Car.numberOfWheels());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment