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")
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.
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.
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.
No, you can not return multiple values like this in C. A function can have at most one single return value.
Function definition:
public ReturnTwoValues(someInput: string): [string, boolean] {
const text = "hello"
const value = true
return [text, value]
}
Caller:
let [text, value] = ReturnTwoValues("someinputstring")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With