JakeDK
JakeDK

Reputation: 1246

Infer type from return value with JSDoc

What is the correct way to assign type from a functions return type?

async function getFood(){
  const food = await {fruit: 'banana', qty: 3}
  return food
}

/** 
 * made up syntax
 * @type {returnOf getFood} 
 * */
let doesntWork;

/** @type {{fruit: string, qty: number}} */
let worksButNoInferring

let worksButRequiresCallingFunction = getFood()

As evidenced by VSCode, the return type is available. I just don't know how to get it without calling the function.

enter image description here

Upvotes: 3

Views: 2189

Answers (1)

Obscurus Grassator
Obscurus Grassator

Reputation: 165

It is probably not according to the JSDoc specification, but VS Code supports Typescript syntax in JSDoc.

async function getFood(){
    const food = await {fruit: 'banana', qty: 3}
    return food
}

/** @type { typeof getFood extends (...args: any[]) => infer U ? U : any } */
let test;

Playground

Upvotes: 9

Related Questions