1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Passing generic Pipe that implements PipeTransform in Angular

Discussão em 'Angular' iniciado por John Rousseau, Setembro 25, 2024.

  1. I have a bunch of custom pipes like this:

    @Pipe({ name: 'appPadThree', pure: true, standalone: true })
    @Injectable()
    export class PadThreePipe implements PipeTransform {
    transform(value: number): string {
    // Code
    }
    }


    I'm trying to write a generic function to use .transform() but .transform() doesn't exist on type Pipe.

    Attempt 1:

    pipeData<T>(value: string, pipeName: T): string {
    const pipeWorker = inject(pipeName);
    return pipeWorker.transform(value);
    }


    Attempt 2:

    pipeData<T extends PipeTransform>(value: string, pipeRef: T): string {
    return pipeRef.transform(value);
    }


    Error: Argument of type 'Pipe' is not assignable to parameter of type 'PipeTransform'. Property 'transform' is missing in type 'Pipe' but required in type 'PipeTransform'.
    ​

    This code worked prior to the Angular 18 / standalone upgrade. It didn't use generics and was ugly.

    pipeData(value: any, pipeName: any): any {
    const pipeWorker = this.injector.get(pipeName);
    return pipeWorker.transform(value);
    }


    How can I write a generic function that takes a Pipe as the type, knowing that it implements PipeTransform?

    Continue reading...

Compartilhe esta Página