使用 JSDoc 从返回值推断类型

Jak*_*eDK 3 jsdoc

从函数返回类型分配类型的正确方法是什么?

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()
Run Code Online (Sandbox Code Playgroud)

VSCode 证明,返回类型是可用的。我只是不知道如何在不调用该函数的情况下获取它。

在此输入图像描述

小智 9

它可能不符合 JSDoc 规范,但 VS Code 支持 JSDoc 中的 Typescript 语法。

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

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

操场