【问题标题】:Extending and replacing existing Interfaces in TypeScript扩展和替换 TypeScript 中的现有接口
【发布时间】:2020-05-01 22:09:01
【问题描述】:

我目前正在为 Mongoose 开发插件。作为其中的一部分,选项接口需要扩展,因为它可以包含其他属性。为此,我正在执行以下操作。

我使用Declaration-Merging,所以我创建了一个像这样的 TypingsFile

SomeTypings.d.ts

declare Interface QueryFindOneAndUpdateOptions {
  MyCustomField: string
}

我还在 tsconfig.json 中包含了这个 Typings 文件

tsconfig.json

include : [
  ...
  "./src/types/SomeTypings.d.ts"
]

很遗憾,这不起作用。仅当我在同一个文件中声明两个具有相同名称的接口时,声明合并才有效。导入和定义接口会引发命名冲突。

有什么办法可以解决这个问题吗?

【问题讨论】:

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


    【解决方案1】:

    好的,所以答案很简单。基本上我犯了2个错误

    1. 我没有声明包含我要扩展的接口的模块
    2. 我没有在 tsconfig CompilerOptions 中添加 typeRoots(我的问题中的“包含”与此无关)

    1 - 类型 (mongoose.d.ts)

    我在 ./src/types 中创建了一个 mongoose.d.ts(名称并不重要,但我更喜欢将其命名为我扩展的模块)文件。在这里我像这样扩展我的接口

    mongoose.d.ts

    interface SpecialOptions {
      verySpecialStuff: string
      enable: boolean
    }
    
    declare module 'mongoose' {
      export interface ModelOptions {
        MyNewKey: SpecialOptions
      }
    }
    

    这将通过 MyNewKey

    扩展 mongoose 中现有的接口 ModelOptions

    2 - 配置编译器

    默认情况下,编译器只会检查 ./node_modules/@types 的类型。所以你需要告诉它也包括你的自定义类型。为此,compilerOptions 需要像这样扩展

    tsconfig.json

    {
    // ...
      "compilerOptions" : {
        // ...
        "typeRoots" : [
          "src/types",
          "node_modules/@types"
        ]
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-07-06
      • 2021-03-16
      • 2015-04-01
      • 2017-09-23
      • 2020-10-30
      • 2020-06-09
      • 2017-10-21
      • 2020-04-09
      相关资源
      最近更新 更多