【问题标题】:Importing pipe throwing Typescript property does not exist error导入管道抛出 Typescript 属性不存在错误
【发布时间】:2017-12-17 05:47:40
【问题描述】:

我正在使用 ionic 并创建了一个自定义管道,该管道接受一个表示图像数据的对象并返回该图像的 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 导入组件以供使用之前,我收到以下错误...

打字稿错误

“字符串”类型上不存在属性“图像版本”。

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

【问题讨论】:

    标签: javascript angular typescript ionic3


    【解决方案1】:

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

    你可能有一个自定义类:

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

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

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

    【讨论】:

    • 我知道这很简单,我没有看到。实际上,将图像作为类也是一个好主意,所以我也这样做了。我刚刚将 value: string 更改为 value: any 以确保它可以接受一个类和一个对象。
    猜你喜欢
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    • 2016-08-27
    • 2020-08-28
    • 2018-06-01
    • 1970-01-01
    • 2019-07-07
    相关资源
    最近更新 更多