Search code examples
angulartypescriptinput

Unable to add types to input with transform functionality


I have the following snippet:

  filterCriteria = input.required({
    transform: (value: string) => value.toLocaleLowerCase(),
    alias: 'listCriteria'
  });

I would like to transform the input with a transform method. As soon as I add types to the input.required part, it does not compile anymore with the following error message:

TS2322: Type '(value: string) => string' is not assignable to type 'undefined'.

It is reproducible in this Stackblitz example:

https://stackblitz.com/edit/signal-inputs-deborahk-rpofup?file=src%2Fsnacks%2Fsnack-list.component.ts

My question is, why does this not work? The background of my question is the fact that my template is not happy with the provided type by filterCriteria.


Solution

  • If you use transform fn with an input, you should add a second generic parameter to required <T, transformT>.

    TransformT is the type of the transform function's parameter, T is the return type.

    When you specify an input transform, the type of the transform function's parameter determines the types of values that can be set to the input in a template. I think that's why you should add this generic additionally.

    In your example:

    filterCriteria = input.required<string, string>({
        transform: (value: string) => value.toLocaleLowerCase(),
        alias: 'listCriteria'
      });