Jordan
Jordan

Reputation: 2523

Importing pipe throwing Typescript property does not exist error

I'm using ionic and have created a custom pipe that takes an object representing image data and returns a URL to that image.

The pipe file looks like this...

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}`;
    }
  }
}

I have created a pipes.module.ts file in the pipes folder that imports my pipes...

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

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

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

Now before I even import the PipesModule into a component for use I am getting the following error...

Typescript Error

Property 'image_version' does not exist on type 'string'.

I can't understand why this error is coming up when I haven't even attempted to use it yet and it's quite annoying really. Can someone explain why the pipe is being executed and how I can prevent this error from throwing when I haven't passed any data into the pipe yet?

Upvotes: 0

Views: 943

Answers (1)

msmolcic
msmolcic

Reputation: 6557

Well, you declared input value: string which means that you will pass object of type string in it's place in the future. Type of string does not have property of an image_version as the error says, that is an error and your code simply won't work. You're trying to call value.image_version as part of your return result, you will need to change value to be of a proper type, not sure which it is in your case.

You could probably have a custom class for it:

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

You can then declare a value: MyImage as type of MyImage class and Typescript will be fine with it since it contains both properties, image_version and original_image_name unlike string type.

Also, nothing is being executed really, it's just the TypeScript's static-type checking, which prevents you from doing stupid mistakes like this. If you don't want to use static-type checking features, you could also just set it as value with no type specified. That way you can pass whatever you want and it will crash at runtime if it's a wrong type of an object instead.

Upvotes: 2

Related Questions