Typescript return type
Created By: chatGPT
In TypeScript, when defining a function, specifying the return type is important for ensuring that the function produces the expected result. Using return types helps in documenting the purpose and behavior of the function, making the code more maintainable and less prone to errors. Here's how to define a return type:
function add(x: number, y: number): number {
return x + y;
}
In the example above, the function
add
takes two parameters, x
and y
, both of type number. The return type is also specified as number, indicating that the function will return a numeric value.function greet(name: string): string {
return `Hello, ${name}!`;
}
Here's another example where the function
greet
takes a string parameter name
and returns a greeting message formatted as a string. The use of the return type makes it clear to the developer what type of data to expect back from the function.function randomBoolean(): boolean {
return Math.random() < 0.5;
}
Additionally, you can return values of different types using union types. For instance, if you want a function that can return either a string or a number, you can do it like this:
function getValue(): string | number {
if (Math.random() > 0.5) {
return 'Hello';
}
return 42;
}
In this example, the
getValue
function uses a union type string | number
for its return type, meaning it may return either a string or a number, depending on the condition specified within the function.function fetchData(): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Data loaded');
}, 1000);
});
}
You can also specify that a function returns a Promise when dealing with asynchronous operations. In the
fetchData
function, the return type is Promise<string>
, indicating that it will eventually resolve to a string after an asynchronous operation.function processValue(value: number): void {
console.log(value);
}
If a function doesn't return a value, you can use the void return type. The
processValue
function takes a number, logs it to the console, and does not return anything.function concatStrings(a: string, b: string): string {
return a + b;
}