Typescript function
Created By: chatGPT
TypeScript is a superset of JavaScript that adds static typing to the language. In this tutorial, we will create a simple TypeScript function. We'll learn how to define a function, specify the types of parameters, and define the return type.
function greet(name: string): string {
return `Hello, ${name}!`;
}
const userName: string = 'Alice';
console.log(greet(userName));
In the example above, we defined a function called
greet
. It takes a single parameter, name
, which is of type string. The function also has a return type of string. In the last part, we declare a variable userName
and pass it to the greet
function, logging the result to the console.function add(a: number, b: number): number {
return a + b;
}
const sum: number = add(5, 10);
console.log(`The sum is: ${sum}`);
Here, we created another function called
add
that takes two parameters, a
and b
, both of type number. The function returns their sum also as a number. We then invoke it with two numbers and log the output to the console.function multiply(a: number, b: number): number {
return a * b;
}
console.log(`5 multiplied by 10 is: ${multiply(5, 10)}`);
This is another example of a function named
multiply
that performs multiplication. It takes two numbers and returns their product. The result is immediately logged to the console.function isEven(num: number): boolean {
return num % 2 === 0;
}
console.log(`Is 4 even? ${isEven(4)}`);
The
isEven
function checks if a number is even. It takes a number as a parameter and returns a boolean indicating whether the number is even. We call this function and log the result.function calculateCircleArea(radius: number): number {
return Math.PI * radius * radius;
}
console.log(`Area of circle with radius 5: ${calculateCircleArea(5)}`);
Finally, we created a function called
calculateCircleArea
that calculates the area of a circle given its radius. The area is calculated using the formula πr². The output is displayed in the console, showcasing how we can work with mathematical functions in TypeScript.interface Person {
name: string;
age: number;
}
function greetPerson(person: Person): string {
return `Hello, my name is ${person.name} and I am ${person.age} years old.`;
}
const individual: Person = { name: 'John', age: 30 };
console.log(greetPerson(individual));
Using interfaces in TypeScript allows us to define the structure of an object. In the
greetPerson
function, we use an interface named Person
that has properties name
and age
. The function uses this interface to ensure that the passed argument satisfies the expected structure.function fetchData(url: string): Promise<any> {
return fetch(url)
.then(response => response.json())
.catch(error => console.error('Error fetching data:', error));
}
fetchData('https://api.example.com/data')
.then(data => console.log(data));