【问题标题】:Unable to declare an extension method to the App (ionic-angular)无法向应用程序声明扩展方法(离子角度)
【发布时间】:2019-03-13 13:21:52
【问题描述】:

在我的 /ext/app-entension.ts ("typescript": "^2.4.2") 中,我声明了 App (ionic-angular) 类的扩展函数:

// **error #1** from the list below
import { NavController, App } from "ionic-angular"; 

interface App {
    getMyCoolNav(): NavController;
}

// **error #2** from the list below
App.prototype.getMyCoolNav = function(this: App): NavController {
    // logic to define suitable nav combining the following calls
    // this.getRootNavs && this.getActiveNavs
    // **error #3** from the list below
}

在我的页面中,我可以导入这个扩展并毫无问题地使用它:

import { NavController, App } from "ionic-angular";
import '../ext/app-extensions'

// **error #4** from the list below
this.app.getMyCoolNav().push(MyCoolPage);

它在运行时运行良好,而 VS Code / Typescript 却让我遇到各种错误:

  1. import:[ts] 导入声明与“App”的本地声明冲突。
  2. 原型分配:[ts] 属性“getMyCoolNav”在类型“App”上不存在。
  3. this 原型中的用法:[ts] 属性 'getRootNavs' 在类型“App”上不存在。
  4. 在我的页面中:[ts] 属性“getMyCoolNav”在类型“App”上不存在。

我的扩展方法注册有什么问题?

【问题讨论】:

标签: angular typescript ionic-framework typescript2.0


【解决方案1】:

您需要使用接口扩充模块,以告知编译器新接口。例如

文件 test.ts

export class Test {
    getSomething(): string {
        return "something";
    }
}

文件 testExtensions.ts

import { Test } from "./test";

declare module "./test" {
    interface Test {
        getSomethingElse(): string;
    }
}

Test.prototype.getSomethingElse = function(): string {
    return "somethingElse";
}

这确实告诉编译器有关接口的信息,您应该能够根据需要扩展原型。见https://www.typescriptlang.org/docs/handbook/declaration-merging.html,搜索“Module Augmentation”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    • 2014-07-29
    • 2020-06-10
    • 1970-01-01
    • 2015-01-09
    • 2013-12-29
    相关资源
    最近更新 更多