导入管道抛出 Typescript 属性 不存在错误

Importing pipe throwing Typescript property does not exist error

我正在使用 ionic 并创建了一个自定义管道,该管道采用表示图像数据的对象和 returns 到该图像的 URL。

管道文件如下所示...

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'eventImageLink',
})
export class EventImageLinkPipe implements PipeTransform {
  /**
   * Takes a value and makes it lowercase.
   */
  transform(value: string, ...args) {
    if(value){
      return `//res.cloudinary.com/***/image/upload/w_${window.screen.width},d_item_placeholder_e0lign.jpg/${value.image_version}/${args[0]}/${value.original_image_name}`;
    }
  }
}

我在 pipes 文件夹中创建了一个 pipes.module.ts 文件来导入我的管道...

import { NgModule } from '@angular/core';
import { EventImageLinkPipe } from './event-image-link/event-image-link';

@NgModule({
  declarations: [
    EventImageLinkPipe
  ],
  imports: [

  ],
  exports: [
    EventImageLinkPipe
  ]
})
export class PipesModule {}

现在,在我将 PipesModule 导入组件以供使用之前,我收到以下错误...

Typescript 错误

属性 'image_version' 在类型 'string' 上不存在。

我什至还没有尝试使用它,我不明白为什么会出现这个错误,这真的很烦人。有人可以解释为什么要执行管道,以及当我还没有将任何数据传递到管道中时如何防止抛出此错误?

嗯,你声明了输入value: string,这意味着你将来会在它的位置传递字符串类型的对象。正如错误所说,string 的类型没有 image_version 的 属性,这是一个错误,您的代码根本无法运行。您正在尝试调用 value.image_version 作为 return 结果的一部分,您需要将 value 更改为正确的类型,但不确定您的情况。

您可能有一个自定义的 class:

export class MyImage {
    image_version: string;
    original_image_name: string;
}

然后您可以将 value: MyImage 声明为 MyImage class 的类型,Typescript 可以使用它,因为它包含两个属性,image_versionoriginal_image_name 不同于 string 类型。

此外,实际上并没有执行任何操作,这只是 TypeScript 的静态类型检查,它可以防止您犯下这种愚蠢的错误。如果您不想使用静态类型检查功能,您也可以将其设置为 value 而不指定类型。这样你就可以传递任何你想要的东西,如果它是错误类型的对象,它将在运行时崩溃。