如何在被定义为"any"的第三方TypeScript接口中增加属性?

12 浏览
0 Comments

如何在被定义为"any"的第三方TypeScript接口中增加属性?

如何扩展这个模块以更严格地定义"data"属性的类型?

我尝试了以下代码:

// 在/app/typings.d.ts中

declare module 'ThirdPartyModule' {

interface IMyCustomType {}

interface ThirdPartyInterface {

// 导致编译错误:后续的属性声明必须具有相同的类型。 "data"属性必须是"type"类型,但这里的类型是"IMyCustomType"。

data: IMyCustomType;

}

}

但是这给了我一个编译错误:"后续的属性声明必须具有相同的类型。 "data"属性必须是"type"类型,但这里的类型是"IMyCustomType"。

如果第三方模块将属性定义为实际类型,像这样:

// 在/node_modules/third-party-module/index.d.ts中

declare module 'ThirdPartyModule' {

interface IAnotherThirdPartyInterface {

something: string;

}

interface ThirdPartyInterface {

data: IAnotherThirdPartyInterface;

}

}

我可以简单地让我的"IMyCustomType"接口扩展这个第三方类型:

// 在/app/typings.d.ts中

declare module 'ThirdPartyModule' {

interface IMyCustomType extends IAnotherThirdPartyInterface {}

interface ThirdPartyInterface {

data: IMyCustomType;

}

}

然而,由于类型被定义为"any",我无法扩展它:

// 导致编译错误:'any'只能引用类型,但在这里被用作值。

interface IMyCustomType extends any {}

0
0 Comments

问题的出现原因是:在第三方的TypeScript接口中,如果属性的类型是"any",我们无法重新定义该属性。

解决方法是:定义一个新的属性,并将原始对象与这个新属性进行扩展。尽管这种解决方法并不适用于所有情况,但如果属性是一个类的属性,那么可以实现。在这种情况下,我们提到了"hapi"。由于该属性在"Server"类上,我们可以定义一个新的类型化版本的属性。

在"hapi.augment.ts"文件中定义了一个新的类型化属性,并将其添加到"hapi"模块的声明文件中。然后,我们使用Object.defineProperty方法将这个新属性添加到"Hapi.Server.prototype"上。

在"usage.ts"文件中,我们先导入"hapi.augment.ts"文件,然后创建一个新的Hapi.Server实例。接下来,我们启动服务器,并将"typedApp.myData"属性设置为"Here"。最后,我们定义了一个路由处理程序,当访问根路径时返回"typedApp.myData"属性的值。

这个解决方法非常有趣!它让我离我想要的结果更近了一步。感谢你提供的示例!

0