typescript - 如何通过函数公开枚举的属性
问题描述
我正在学习打字稿并遇到过这种情况:
我想公开一些关于枚举的信息,如下所示:
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()
解决方案
推荐阅读
- django - 如何在没有模型/数据库的情况下显示来自 Django 表单 ImageField 输入的图像
- python - 在 Windows 10 上找不到 Python 3.8.2 路径
- vue.js - 在插值哈巴狗模板中使用 Vue 道具
- audio - XAudio2 语音池
- c# - 动态传递类型参数
- c# - Swagger Codegen IO:更改服务命名约定和昵称
- flutter - Y 轴百分比仅显示两个值 0% 和 100% - Flutter Charts
- assembly - 如何在不覆盖返回地址的情况下从函数返回并将值存储在堆栈中?
- r - 德雷克计划拟合 lmer 模型失败
- python - 如何在列表中减去奇数索引值并添加偶数索引值?(a-b+c-d+e)