I am learning typescript and have been confronted with this scenario:
I want to expose some information about an enum like so:
const companyName: string = Company.apple.nameAsString()
This is to resemble a similar feature the Swift language has:
Swift
enum Company {
case apple
case honeywell
func nameAsString() -> String {
switch self {
case .apple: return "Apple"
case .honeywell: return "Honeywell"
}
}
func tickerSymbolAsString() -> String {
switch self {
case .apple: return "APPL"
case .honeywell: return "HON"
}
}
So far, I've implemented this:
export enum Company {
apple = "Apple",
honeywell = "Honeywell",
}
export namespace Company {
export function nameAsString(company: Company): string {
return company.toString();
}
export function tickerSymbolAsString(company: Company): string {
switch (company) {
case Company.apple:
return "APPL";
case Company.honeywell:
return "HON";
}
}
}
I don't like this implementation because when using it, it feels too verbose:
name: Company.nameAsString(Company.apple)
Is there a way to implement something that would allow me to do
const companyName: string = Company.apple.nameAsString()