【问题标题】:How to type an imported object using JSDoc type annonations?如何使用 JSDoc 类型注释键入导入的对象?
【发布时间】:2021-04-13 01:28:30
【问题描述】:

我有以下代码:

// NoteList.server.js

import {prisma} from './db.server'; // how to type this using JSDoc???
import SidebarNote from './SidebarNote';

export default function NoteList({searchText}) {
  const notes = prisma.note.findMany({
    where: {
      title: {
        contains: searchText ?? undefined,
      },
    },
  });

  // Now let's see how the Suspense boundary above lets us not block on this.
  // fetch('http://localhost:4000/sleep/3000');

  return notes.length > 0 ? (
    <ul className="notes-list">
      {notes.map((note) => (
        <li key={note.id}>
          <SidebarNote note={note} />
        </li>
      ))}
    </ul>
  ) : (
    <div className="notes-empty">
      {searchText
        ? `Couldn't find any notes titled "${searchText}".`
        : 'No notes created yet!'}{' '}
    </div>
  );
}

导入的prisma 对象是我的node_modulesPrismaClient 类的一个实例。我也有一个index.d.ts,所以我希望输入prisma 对象,以便在VS Code 中自动完成。

我知道我可以使用 JSDoc 导入PrismaClient 类型如下:

/**
 * @typedef { import("@prisma/client").PrismaClient } PrismaClient
 */

但是,我现在很难在导入时将 PrismaClient 类型分配给 prisma 对象。我知道在将类型传递给函数时如何将类型分配给对象/值:

/**
 * @param {PrismaClient} prisma - My `PrismaClient` instance
 */
function foo(prisma) {
  // I now get autocompletion on the `prisma` instance
  // because VS Code knows it's of type `PrismaClient`
}

但我不知道如何为导入做同样的事情。谁能帮我吗?这是JSDoc cheatsheet 的链接,以防万一。

编辑:另外,为了添加更多信息,prisma 实例是从该文件导入的:

// db.server.js

import {PrismaClient} from 'react-prisma';

export const prisma = new PrismaClient();

您还可以在此处找到包含此示例代码的 repo:https://github.com/prisma/server-components-demo

感谢@Mino 的建议,我也在导出时尝试了这个,但我仍然没有得到任何自动补全:

/**
 * @typedef { import("@prisma/client").PrismaClient } PrismaClient
 */
import {PrismaClient} from 'react-prisma';


/**
 * @const {PrismaClient}
 */
export const prisma = new PrismaClient();

【问题讨论】:

    标签: javascript typescript visual-studio-code typescript-typings jsdoc


    【解决方案1】:

    感谢@Mino 的建议,我解决了这个问题,我宁愿查看导出对象的文件,而不是专注于输入导入。我通过将其添加到db.server.js 文件来获得自动完成功能:

    /**
     * @typedef { import("@prisma/client").PrismaClient } PrismaClient
     */
    import {PrismaClient} from 'react-prisma';
    
    
    /**
     * @type {PrismaClient}
     */
    export const prisma = new PrismaClient();
    
    

    【讨论】:

    • 同时确保node_modules 在您希望自动完成工作时正确安装。
    【解决方案2】:

    你能分享你导出prisma对象的./db.server的内容吗? 因为如果在该文件中正确键入了导出,则导入应该无需执行任何操作即可工作。

    【讨论】:

    • 哈,好点子!我将导出添加到问题中。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-13
    • 2023-01-10
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多