You are here: Home / Topics / Creating Class in Typescript

Creating Class in Typescript

Filed under: TypeScript on 2024-03-14 11:08:37

TypeScript offers full support for the class keyword introduced in ES2015.


Class Members
Here’s the most basic class - an empty one:
class Point {}
This class isn’t very useful yet, so let’s start adding some members.


Fields
A field declaration creates a public writeable property on a class:
class Point {
x: number;
y: number;
}
const pt = new Point();
pt.x = 0;
pt.y = 0;


As with other locations, the type annotation is optional, but will be an implicit any if not specified. Fields can also have initializers; these will run automatically when the class is instantiated:


class Point {
x = 0;
y = 0;
}
const pt = new Point();
// Prints 0, 0
console.log(`${pt.x}, ${pt.y}`);


Example 1: 
Index.ts:
class Person {
// By default name & age have public access specifier.
name = 'George';

age = 76;
}
let person1 = new Person();
console.log(`Name is : ${person1.name}, & Age is $
{person1.age}`);


Note: The following typescript code will convert to javascript using tsc compiler & the javascript code will look like as follows:


index.js: (Incase of tsc index.ts)
var Person = /** @class */ (function () {
function Person() {
this.name = 'George';
this.age = 76;
}
return Person;
}());


var person1 = new Person();
console.log("Name is : " + person1.name + ", & Age is " +
person1.age);


index.js: (tsc index.ts --target es2015 or tsc index.ts --target es6)


class Person {
constructor() {
this.name = 'George';
this.age = 76;
}
}
let person1 = new Person();
console.log(`Name is : ${person1.name}, & Age is $
{person1.age}`);


Example 2: 
index.ts:
class Person {
private name: string;
private age: number;

constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): void {
console.log(`Hello, my name is ${this.name} and I'm $
{this.age} years old.`);
}
}
let person1 = new Person('George', 23);
person1.greet();


Note: Compile index.ts file using tsc index.ts then execute the javascript file either using HTML file or using node fileName.js command.

About Author:
J
Java Developer     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.