How do you return multiple values from a typescript function

ID : 274557

viewed : 34

Tags : typescripttypescript





Top 4 Answer for How do you return multiple values from a typescript function

vote vote

90

Function definition:

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

Caller:

let [text, value] = ReturnTwoValues("someinputstring") 
vote vote

83

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 
vote vote

73

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 

Playground Link

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.

vote vote

60

Top 3 video Explaining How do you return multiple values from a typescript function







Related QUESTION?