【问题标题】:Infer type from return value with JSDoc使用 JSDoc 从返回值推断类型
【发布时间】:2021-05-05 15:25:26
【问题描述】:

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

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()

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

【问题讨论】:

标签: jsdoc


【解决方案1】:

可能不符合 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;

Playground

【讨论】:

  • 这超出了我的想象,但它确实有效。 ?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-15
  • 2019-12-06
  • 2021-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多