Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you return multiple values from a typescript function

Tags:

typescript

I'd like a Typescript function to return multiple values. How do I do this? Also - how do I declare the types?

For example I want to achieve something like this:

let [text, value] = ReturnTwoValues("someinputstring")
like image 469
Lars Avatar asked Aug 21 '20 16:08

Lars


People also ask

How can I return multiple values from a function?

If we want the function to return multiple values of same data types, we could return the pointer to array of that data types. We can also make the function return multiple values by using the arguments of the function.

Can TypeScript function return multiple types?

Use a union type to define a function with multiple return types in TypeScript, e.g. function getValue(num: number): string | number {} . The function must return a value that is represented in the union type, otherwise the type checker throws an error.

Can we return 2 values from a function in JavaScript?

JavaScript doesn't support functions that return multiple values. However, you can wrap multiple values into an array or an object and return the array or the object.

Can you return multiple values from a function using return statement?

No, you can not return multiple values like this in C. A function can have at most one single return value.


2 Answers

Function definition:

public ReturnTwoValues(someInput: string): [string, boolean] {
    const text = "hello"
    const value = true
    return [text, value]
}

Caller:

let [text, value] = ReturnTwoValues("someinputstring")
like image 185
Lars Avatar answered Oct 12 '22 16:10

Lars


public ReturnTwoValues(someInput: string): {text:string, value:boolean} {
    const text = "hello"
    const value = true
    return {text, value}
}

let {text, value} = ReturnTwoValues("some irrelevant string");

console.log(text) //output hello
console.log(value) // output value
like image 24
Juan Vilar Avatar answered Oct 12 '22 16:10

Juan Vilar