In TypeScript, basic types like number, string, and boolean can be explicitly declared.
const a: number = 0;
This task involves creating a function with typed parameters and testing the behavior when the wrong type is passed.
Example: In this case, sumArray accepts an array of numbers and an any type parameter but returns a fixed value.
function sumArray(a: number[], b: any): number {
return 10;
}
let c = sumArray([10], "test"); // Calling the function
console.log(c); // Output: 10
Note: Passing a string as the second parameter still works because b is of type any.
TypeScript allows us to define custom object types using type or interface.
Example: Defining a Person type with optional properties.
type Person = {
name: string,
age: number,
extra?: number // Optional property
}
let omar: Person = {
name: "Omar",
age: 25
};
console.log(omar.name, omar.age); // Output: Omar 25
Here, the extra property is optional, which means it’s not mandatory to include it when creating a Person object.
You are defining a class Circle with properties and methods. Here, you’ll implement additional methods as per the TODO comments.
Example: Defining the Circle Class and Adding Methods
type Point = {
x: number,
y: number
}
class Circle {
center: Point;
radius: number;
constructor(center: Point, radius: number) {
this.radius = radius;
this.center = center;
}
// Method to calculate the area of the circle
calculateArea() {
return Math.PI * Math.pow(this.radius, 2);
}
// Method to scale the circle by multiplying the radius by a factor
scale(factor: number) {
this.radius *= factor;
}
// Method to move the center point of the circle
move(dx: number, dy: number) {
this.center.x += dx;
this.center.y += dy;
}
}
Now, instantiate the circle and test its functionality:
let c1 = new Circle({ x: 0, y: 0 }, 2);
console.log(c1.calculateArea()); // Output: 12.566370614359172 (π * r²)
c1.scale(2); // Scales the radius by 2
console.log(c1.calculateArea()); // Output: 50.26548245743669 (New area after scaling)
c1.move(10, 5); // Moves the center by 10 units in x and 5 units in y
console.log(c1.center); // Output: { x: 10, y: 5 }
You also define a Person class and extend it with a Teacher class, demonstrating inheritance and method overriding.
Example: Defining Person and Teacher Classes
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello from ${this.name}`);
}
}
class Teacher extends Person {
// Overriding the greet method
greet() {
console.log(`HELLO Guys from ${this.name}`);
}
// New method specific to the Teacher class
teach() {
console.log('I am teaching web dev');
}
}
const t = new Teacher("Omar", 25);
t.greet(); // Output: HELLO Guys from Omar
t.teach(); // Output: I am teaching web dev
The Teacher class inherits from Person and overrides the greet method while also adding a new method teach.