Tim Cobra
Tim Cobra

Reputation: 131

Typescript and Angular Filters

I want to use one of my Angular Filters as a function in my controller. I found the answer here: How to use a filter in a controler

In fact I used the last answer as it provided exactly what I needed. My JS looks like this:

    var MyFunc = $filter('MyGreatFilter');
    var resp = MyFunc(6);

And it works fine. However, I'm using Typescript and I can't figure out how to give it the correct type. Obviously without any type I get the error:

error TS2349: Cannot evoke an expression whose type lacks a call signature

When I add this type to my controller's interface:

MyFunc(val:number): string;

I get an error I don't understand:

error TS2322: Type {} is not assignable to type '(val: number) => string'

The function takes a number as a parameter and returns a string. Any ideas on how to Type the Filter function MyFunc?

Thanks.

Upvotes: 0

Views: 617

Answers (1)

Tim Cobra
Tim Cobra

Reputation: 131

I found the answer in another part of the code that I'm working on that someone else (much cleverer than me) wrote. You need to add an Typescript interface above the filter:

interface IFilterMyGreatFilterName {
(value: number): string;
}

function MyGreatFilter () {
    return function (item:number) {
        // Filter stuff and return a string
    };
}

And then call the function in a slightly different way than I showed above:

var resp = $filter<IFilterMyGreatFilterName>('MyGreatFilter')(aNumValue);

Upvotes: 1

Related Questions