gpt4 book ai didi

typescript - 通过模块扩充向现有 TypeScript 接口(interface)添加属性无效

转载 作者:搜寻专家 更新时间:2023-10-30 20:57:17 27 4
gpt4 key购买 nike

我有一个依赖于 @types/hapi 的节点应用程序.我想向该模块中定义的其中一个类添加一个属性。我尝试通过模块扩充定义我的新属性:

// my-custom-hapi-typings.d.ts
import * as hapi from 'hapi';

declare module hapi {
interface Server {
myProperty: string;
}
}

这不会导致任何编译器错误,但它也不会将 myProperty 属性添加到 Server 类。当我尝试像这样引用该属性时,我的项目中的其他地方仍然出现错误:

// my-other-file.ts
import * as hapi from 'hapi';

const server = new hapi.Server({ ... });

// error: Property 'myProperty' does not exist on type 'Server'.
server.myProperty = 'hello';

为什么 TypeScript 编译器似乎忽略了我的 .d.ts 文件?我是否需要“导入”该文件或以某种方式让 TypeScript 编译器知道该文件存在?我的印象是,只要在源目录中放置一个 .d.ts 文件就足以让 TypeScript 接受这些增强。

最佳答案

这是你的问题:

declare module hapi {

这实际上定义了一个 namespace ,使用早于 ES6 模块的旧语法,这些模块曾经被称为“内部模块”。编写 module hapi 与编写 namespace hapi 相同,这是当今首选的语法。 More on namespaces vs modules here.

收件人declare an external module你只需要将模块名称放在引号中:

[...] use a construct similar to ambient namespaces, but we use the module keyword and the quoted name of the module which will be available to a later import.

换句话说,只需将 hapi 放在引号中即可:

declare module "hapi"

现在你有了一个ambient(my-custom-hapi-typings.d.ts不需要直接导入)外部模块 定义(声明 import "hapi" 为您提供的内容),您可以扩充其中声明的内容。

如果您将鼠标悬停在 module hapimodule "hapi"in the Playground您会在工具提示中看到不同之处:

enter image description here enter image description here

是的,由于其背后的历史,它很微妙且令人困惑。

关于typescript - 通过模块扩充向现有 TypeScript 接口(interface)添加属性无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46917140/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com