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.
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.
Share Improve this question edited Jul 19, 2016 at 14:50 Sergei Basharov asked Jul 19, 2016 at 14:43 Sergei BasharovSergei Basharov 53.9k78 gold badges207 silver badges352 bronze badges1 Answer
Reset to default 15You 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
).