增强TypeScript中声明的命名空间中的接口 [英] Augmenting an interface that lives in a declared namespace in TypeScript

查看:86
本文介绍了增强TypeScript中声明的命名空间中的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在声明的角度命名空间(来自"@ types/angular")内扩充 IHttpPromise< T> .这样我就可以编写 $ http.then(...).myCustomMethod(...).

I want to augment the IHttpPromise<T> inside the declared angular namespace (from "@types/angular"). So that I'll be able to write $http.then(...).myCustomMethod(...).

我能够通过编写以下代码轻松地在全局上下文中扩展接口:

I was able to augment interfaces in the global context easily by just writing:

interface JQuery {
    $custom: string;
}

对于名称空间内的接口,显然不起作用.尝试了几件事,例如再次声明 angular 命名空间并将增强接口放入其中,但这和其他许多变体均无效.

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.

请注意,我没有使用(外部)模块.

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;
    }
}

import语句的内容本身并不重要.我们必须进行导入,以使TS将这个文件作为一个模块来起作用.所以这也行得通:

The import statement's content itself is not important. We have to do an import to make TS treat this file as a module for this to work. So this would've also worked:

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

此处结尾处对此进行了记录.

This is documented at the end here.

这篇关于增强TypeScript中声明的命名空间中的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆