Home > database >  typescript return destructuring?
typescript return destructuring?

Time:10-22

function print(): (number, string) {
    return {1,'my'}
}

Above code shows error, I expect I can use const {num, my} = print(). What's the right way to specify return type?

CodePudding user response:

Try to use a tuple. It looks like this:

function print(): [number, string] {
    return [1,'my']
}

const [num, my] = print();

See demo in Typescript Playground

CodePudding user response:

You need to return an object which has a string and a number. Now, this object should contain property names - so, let's define the return type and use it in your function

type myReturnType = {
  n: number,
  s: string
}

function print():myReturnType {
   return {n:1,s: 'my'}
}

let {n, s} = print();

Here is the shorthand version of the above code:

function print():{n: number, s: string}{
    return {n:1,s: 'my'}
}

let {n, s} = print();
  • Related