【问题标题】:Typescript: Accessing declare module types打字稿:访问声明模块类型
【发布时间】:2022-01-09 22:17:42
【问题描述】:

对于带有typescript support 的 knexjs,我设置了以下内容:

declare module "knex/types/tables" {
    interface Tables {
        // base tables
        groups: Knex.CompositeTableType<
            // Table
            typeof GroupDB.type,
            // Insert
            typeof GroupDBInsert.type,
            // Update
            typeof GroupDBUpdate.type
        >;
    }
}

它有效。我想重用接口中找到的类型。

import { Tables } from "knex/types/tables";

let tableName: keyof Tables = "groups"

knex/types/tables 会因错误而失败

Unable to resolve path to module 'knex/types/tables'.eslintimport/no-unresolved

我应该怎么做才能访问声明的模块的类型?

【问题讨论】:

  • 您是否已将declare module 部分放入声明 (d.ts) 文件中?
  • @sno2 不。它在一个 .ts 文件中,但我会尝试。它在带有 knexjs 的 .ts 中正常工作并显示正确的表名。
  • @sno2 它仍然失败并出现同样的错误
  • 太糟糕了,看起来您需要三斜杠引用。请参阅此处的文档typescriptlang.org/docs/handbook/modules.html#ambient-modules
  • 您也可以在没有declare module 部分的情况下定期从文件(即knex.ts)导入/导出类型。

标签: typescript import module knexjs


【解决方案1】:

我通过将类型与接口分离来解决它。谢谢@sno2!

export type TableTypes = {
        // base tables
        groups: Knex.CompositeTableType<
            // Table
            typeof GroupDB.type,
            // Insert
            typeof GroupDBInsert.type,
            // Update
            typeof GroupDBUpdate.type
        >;
    };

declare module "knex/types/tables" {
    // eslint-disable-next-line @typescript-eslint/no-empty-interface
    interface Tables extends TableTypes {}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-18
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    相关资源
    最近更新 更多