Sergei Basharov
Sergei Basharov

Reputation: 53950

Make a chain of methods with TypeScript

I have an array of countries defined as a const CountriesList:

[{
    name: "Afghanistan",
    id: "4",
    alpha2Code: "AF",
    alpha3Code: "AFG",
    numericCode: 4
},
...]

I have a static class Countries which is supposed to return differently formatted and filtered countries from the const above.

export class Countries {
public static getCountries() {
    return CountriesList;
}

public static getFilteredCountries(setName: string) {
    return CountriesList
        .filter(function (country, index) {
            return customFilter(setName, country, index)
        });
}

public static formatForSelectInput(items: ICountryIso3166[]) {
    return items.map(function (country) {
        return {
            title: L(country.name),
            data: country.id,
            value: country.name
        };
    })
}
}

Now, as it's TypeScript and it has its own rules, I have no idea how to chain methods to make it work like this:

var countryItems = Countries
    .getFilteredCountries('test')
    .formatForSelectInput();

Should I create a new object, so that not to return bare array, but an array inside a wrapper object with respective methods, or how do I perform the chaining properly?

Please advise.

Upvotes: 5

Views: 11037

Answers (1)

WouterH
WouterH

Reputation: 1356

You want to chain methods, so you want to call them on an object, not a static class. So something like removing the static from Countries and changing your code to

var countryItems = new Countries()
    .getFilteredCountries('test')
    .formatForSelectInput();

Each method where you want to allow chaining should then end with return this;. You should also declare the return types of your methods (to be the class Countries).

Upvotes: 15

Related Questions