1

So I have this scenario where I choose a filter object to build. The list of filters is stored in an array:

app.constant("filters", () => <IFilterList>[
    (value, label) => <IFilterObject>{ value: value, label: label }
]);

interface IFilterList {
    [index:number]: (value?:string, label?:string) => IFilterObject
}

interface IFilterObject {
   value: string,
   label: string
}

This allows the module that sets the filter being used:

// somemodule.js

app.controller("SomeController", (filters, filterService) => {
    var filter = filters[0]("this value", "this label");

    filterService.change(filter);
});

As you can see doing filters[0] with a magic number is poor to say the least.

In C# I would create a static class which is public so can be used anywhere. Something like:

public static class FilterNames
{
    public const int NameFilter = 0;
}

How would you do the same in AngularJs and TypeScript using the CommonJs module system?

In my mind you would need global variables... is really the best way to do this?

1
  • you can make an enum with the values. :) Commented Jan 12, 2016 at 10:44

1 Answer 1

1

You could make an enum with the values.

enum FilterType {
  NAME, 
  AGE
}

Enum's get numeric values by default, so the 1st one gets the value 0, 2nd one value 1, etc.

You can use it like this:

filters[FilterType.NAME]("this value", "this label");

The enum can be in another file, and you can import it anywhere you want to use it. You can learn more about enums in TypeScript here.

Sign up to request clarification or add additional context in comments.

1 Comment

Sweet, thought there should be something simple to solve this really common problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.