0

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()
timbre timbre
  • 12,648
  • 10
  • 46
  • 77
fingia
  • 504
  • 7
  • 20
  • I understand the desire for the swiftier syntax, but I think this is all typescript can do for you. https://stackoverflow.com/q/28150739/1271826 – Rob Jan 31 '21 at 19:23
  • Needless to say, the company name is not the problem (because you obviously can do `let companyName = Company.apple.toString();`), but rather the ticker symbol, where you are stuck with the more cumbersome syntax. – Rob Jan 31 '21 at 19:26

0 Answers0