Skip to content

Is it possible for a function to return a list of values? #3418

Closed

Description

I'm wondering if it is possible to return a list of values, something like:

function x(){
  return 1,'dsdsq', 45678.45;
}

The aim is to init several variables at the same time, it exists in other languages but I can't find it in TS. Thanks!

Activity

  1. zhongsp commented on Jun 8, 2015

    @zhongsp
    Contributor

    Maybe you could use tuple types:

    function x(): [number, string, number] {
        return [1, 'dsdsq', 45678.45];
    }
    
    var tuple: [number, string, number] = x(),
        t0 = tuple[0],
        t1 = tuple[1],
        t2 = tuple[2];
  2. kitsonk commented on Jun 8, 2015

    @kitsonk
    Contributor

    Largely I assume it isn't present in TypeScript, because it isn't present in JavaScript/EcmaScript and the intent of TypeScript is not to "break" JavaScript, but be able to emit valid JavaScript, which would be hard to do.

    As a way of solving this in a "JavaScript way", ES6 is adding array destructuring assignment and TypeScript allows you to utilise this feature now.

    function x() {
        return [ 1, 'dsdsq', 45678.45 ];
    }
    
    let [a, b, c] = x(); /* a = 1, b = 'dsdsq', c = 45678.45 */

    TypeScript allows you to destructure arrays, even when targeting non-ES6.

  3. RyanCavanaugh commented on Jun 8, 2015

    @RyanCavanaugh
    Member

    If you combine the comments so far, you'll end up at an ideal solution:

    function x(): [number, string, number] {
        return [ 1, 'dsdsq', 45678.45 ];
    }
    
    // a: number, b: string, c: number
    let [a, b, c] = x(); /* a = 1, b = 'dsdsq', c = 45678.45 */

    We can't change the existing JS syntax since the comma operator already has a different meaning here.

  4. Vadorequest commented on Jun 8, 2015

    @Vadorequest
    Author

    Thanks!
    Le 8 juin 2015 18:32, "Ryan Cavanaugh" notifications@github.com a écrit :

    If you combine the comments so far, you'll end up at an ideal solution:

    function x(): [number, string, number] {
    return [ 1, 'dsdsq', 45678.45 ];
    }
    // a: number, b: string, c: number
    let [a, b, c] = x(); /* a = 1, b = 'dsdsq', c = 45678.45 */

    We can't change the existing JS syntax since the comma operator already
    has a different meaning here.

    —
    Reply to this email directly or view it on GitHub
    #3418 (comment)
    .

  5. locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    By DesignDeprecated - use "Working as Intended" or "Design Limitation" instead

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions