简体   繁体   English

增强TypeScript中声明的名称空间中的接口

[英]Augmenting an interface that lives in a declared namespace in TypeScript

I want to augment the IHttpPromise<T> inside the declared angular namespace (from "@types/angular"). 我想在声明的角度命名空间(来自“ @ types / angular”)内增加IHttpPromise<T> So that I'll be able to write $http.then(...).myCustomMethod(...) . 这样我就可以编写$http.then(...).myCustomMethod(...)

I was able to augment interfaces in the global context easily by just writing: 通过编写以下代码,我能够轻松地在全局上下文中扩充接口:

interface JQuery {
    $custom: string;
}

For interfaces inside namespaces, the same doesn't work obviously. 对于命名空间内的接口,显然不起作用。 Tried several things like declaring the angular namespace again and putting the augmented interface inside, but that and other numerous variations didn't work. 尝试了几件事,例如再次声明了angular命名空间并将增强接口放入其中,但是这种方法和其他许多变体都无法正常工作。

Note that I'm not using (external) modules. 请注意,我没有使用(外部)模块。

Found the solution. 找到了解决方案。 Even if you're not using modules, you'll have to do the following in a separate declaration file: 即使您不使用模块,也必须在单独的声明文件中执行以下操作:

import { IHttpPromise } from '@types/angular';

declare module '@types/angular' {
    interface IHttpPromise<T> {
        myCustomMethod(): something;
    }
}

The import statement's content itself is not important. import语句的内容本身并不重要。 We have to do an import to make TS treat this file as a module for this to work. 我们必须进行导入,以使TS将此文件作为一个模块来起作用。 So this would've also worked: 所以这也可以工作:

import * as angular from '@types/angular';

This is documented at the end here . 这在此处最后记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM