Typescript methods
Created By: chatGPT
TypeScript allows you to define methods within your classes and interfaces. Methods are simply functions that are associated with an object. They can have parameters and return types, and they help encapsulate functionality within your classes. Here's a basic example to illustrate this.
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
speak(): string {
return `${this.name} makes a noise.`;
}
}
const dog = new Animal('Dog');
console.log(dog.speak()); // 'Dog makes a noise.'
Method Overloading in TypeScript allows you to create multiple methods within a class that have the same name but different parameter types. The actual implementation will be defined just once. Here’s how to do it.
class MathUtil {
add(a: number, b: number): number;
add(a: string, b: string): string;
add(a: any, b: any): any {
return a + b;
}
}
const util = new MathUtil();
console.log(util.add(5, 10)); // 15
console.log(util.add('Hello, ', 'World!')); // 'Hello, World!'
In TypeScript, optional parameters can be defined in methods by adding a
?
after the parameter name. This indicates that the parameter is not required.class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet(name?: string): string {
return `${this.greeting}, ${name ? name : 'stranger'}`;
}
}
const greeter = new Greeter('Hello');
console.log(greeter.greet()); // 'Hello, stranger'
console.log(greeter.greet('Alice')); // 'Hello, Alice'
Async methods can be defined using the
async
keyword, which allows you to use await
within the method for promises. This simplifies working with asynchronous operations.class DataFetcher {
async fetchData(url: string): Promise<string> {
const response = await fetch(url);
const data = await response.text();
return data;
}
}
const fetcher = new DataFetcher();
fetcher.fetchData('https://api.example.com/data')
.then(data => console.log(data));
Arrow functions can also be used as methods within a class, especially when you want to ensure the correct context for
this
. It is often useful in callback scenarios.class Counter {
count: number = 0;
increment = () => {
this.count++;
console.log(this.count);
}
}
const counter = new Counter();
counter.increment(); // 1
counter.increment(); // 2