AngularJS TypeScript服务错误

zqdjd7g9  于 2023-05-19  发布在  TypeScript
关注(0)|答案(1)|浏览(96)

我在尝试向模块添加服务时遇到此错误。有人能帮我指出出了什么问题吗?
Angular 1.5.11和TypeScript 2.2.2

ERROR in ./source/mainModule.ts
(185,33): error TS2345: Argument of type 'typeof AwesomeService ' is not 
assignable to parameter of type 'Injectable<Function>'.
Type 'typeof AwesomeService ' is not assignable to type '(string | Function)[]'.
Property 'push' is missing in type 'typeof AwesomeService '.

这里是我尝试添加服务的地方

export default angular.module('iris.service', [])
    /* This line throws the error --> */.service('awesomeService', AwesomeService);

在一个单独的文件中,下面是我创建服务的方式

export class AwesomeService extends OtherClass {

    private static $inject = ['configService'];

    constructor() {
        super();
    }
}

更新:

我发现,如果我将AwesomeService更改为一个函数并将其导出,它可以正常工作。有什么方法可以使用类来提供服务吗?看起来@types/angular指定angular.module.service的第二个参数应该是字符串或函数。

kgsdhlau

kgsdhlau1#

是的,你可以做你想做的事情,你只需要写更少的代码。
@types/angular中的类型声明包括以下内容

declare global {
    interface Function {
        $inject?: ReadonlyArray<string>;
    }
}

这增加了Function类型的声明。添加一个可选属性$inject,以允许以类型安全和声明的方式将干净,可读的AngularJS DI注解添加到类和函数中,而不需要难看的类型Assert。
请注意,所有类和函数实际上都是函数。
你的类的问题是,虽然上面的Function类型扩充声明$inject是可选的,但它 * 没有 * 声明当它 * 被 * 指定时,它可能是private
事实上,它在语义上并不是私有的,因为它被AngularJS框架和其他潜在的工具读取。
要解决此问题,只需编写

export class AwesomeService extends OtherClass {

    static $inject = ['configService']; // no private here.

    constructor() {
        super();
    }
}

更详细的答案是,如果一个类型声明了一个私有成员(要做到这一点,它需要是一个类),与另一个类型中的公共成员同名(所有接口成员都是公共的),那么这两个类型被认为是结构不兼容的。
不幸的是,这个错误有点神秘。private $inject声明使类型检查器立即删除service的重载,该重载采用Function类型的值。然后,它尝试重载service,该重载采用Array类型的值并失败。

相关问题