首页 > 解决方案 > 如何通过函数公开枚举的属性

问题描述

我正在学习打字稿并遇到过这种情况:

我想公开一些关于枚举的信息,如下所示:

const companyName: string = Company.apple.nameAsString()

这类似于 Swift 语言具有的类似功能:

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"
      }
  }

到目前为止,我已经实现了这个:

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";
    }
  }
}

我不喜欢这个实现,因为使用它时,感觉太冗长了:

      name: Company.nameAsString(Company.apple)

有没有办法实现一些可以让我做的事情

const companyName: string = Company.apple.nameAsString()

标签: typescript

解决方案


推荐阅读