获取返回的表达式类型 {providers:EnvironmentProviders[]} 在返回函数时不可分配给类型 Provider[]

问题描述 投票:0回答:1

我试图创建这个传递随机数和 GtagId 的函数。 但我在 IntelliJ 中遇到了

Returned expression type {providers: EnvironmentProviders[]} is not assignable to type Provider[]
错误。 然后我尝试将 Provider[] 类型更改为 EnvironmentProviders[] 但收到以下错误消息:

Assigned expression type (nonce: any, gtagId: any) => EnvironmentProviders[] is not assignable to type (nonce: any, gtagId: any) => Provider[] 
Returned expression type {providers: EnvironmentProviders[]} is not assignable to type EnvironmentProviders[] 

我收到错误的代码:

 googleAnalyticsProviders = (nonce, gtagId): Provider[] => {
        return {
          providers: [
            provideGoogleAnalytics(gtagId, { nonce } as IGoogleAnalyticsOptions),
            provideGoogleAnalyticsRouter()
          ]
        };
      };

该函数将在此处调用:

export const appConfig = (nonce: string | null, gtagId: string): ApplicationConfig => {
  return {
    providers: [
      ...googleAnalyticsProviders(nonce, gtagId),
....

有什么想法吗? 谢谢。

angular typescript
1个回答
0
投票

您应该创建一个自定义类型并将其指定为方法返回类型。

export interface GAProvider {
providers:EnvironmentProviders[];
}

然后将方法返回类型更改为GAProvider

googleAnalyticsProviders = (nonce, gtagId): GAProvider  => {
        return {
          providers: [
            provideGoogleAnalytics(gtagId, { nonce } as IGoogleAnalyticsOptions),
            provideGoogleAnalyticsRouter()
          ]
        };
      };
© www.soinside.com 2019 - 2024. All rights reserved.