'How do you return multiple values from a typescript function
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")
Solution 1:[1]
Function definition:
public ReturnTwoValues(someInput: string): [string, boolean] {
const text = "hello"
const value = true
return [text, value]
}
Caller:
let [text, value] = ReturnTwoValues("someinputstring")
Solution 2:[2]
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
Solution 3:[3]
Of course, since a function returns one value, then the only way to return more than one value is to wrap them together in some object; as others have noted in the comments, an array is a kind of object. However, you don't have to create a new object for this, so technically what you're asking for is possible. Here's a solution which uses the function itself as the return value, so it meets the criterion of not creating an object when the function is called.
interface Foo {
x: string,
y: number,
(): Foo
}
const foo = (() => {
foo.x = 'bar';
foo.y = 1;
return foo;
}) as Foo;
let { x, y } = foo();
console.log(x); // bar
console.log(y); // 1
I don't recommend actually doing this, though; since it doesn't return a fresh object each time, it can lead to bugs if you retain a reference to the return value and expect its properties to stay the same.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lars |
| Solution 2 | Juan Vilar |
| Solution 3 | kaya3 |
