gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:22:42 25 4
gpt4 key购买 nike

我正在使用 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 导入组件以供使用之前,我收到以下错误...

typescript 错误

类型“string”上不存在属性“image_version”。

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

最佳答案

好吧,您声明了输入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_namestring 类型不同。

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

关于javascript - 导入管道抛出 Typescript 属性不存在错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45063775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com