如何在TypeScript中按名称从其他文件获取常量?
动态获取常量的可行性问题
常量文件内容
constants-ltr.ts
export const MY_CONST_1_NAME = "foo"; export const MY_CONST_2_NAME = "bar"; export const MY_CONST_3_NAME = "too"; export const MY_CONST_4_NAME = "far";
constants-rtl.ts
export const MY_CONST_1_NAME = "oof"; export const MY_CONST_2_NAME = "rab"; export const MY_CONST_3_NAME = "oot"; export const MY_CONST_4_NAME = "raf";
疑问:能否通过如下方式动态获取对应常量?
import * as LTR from './constants-ltr'; import * as RTL from './constants-rtl'; class Foo { public isRTL:boolean = false; public reference:1|2|3|4 = 1; public make():string { let origin = this.isRTL ? RTL:LTR; return origin[`MY_CONST_${this.reference}_NAME`]; } }
业务场景补充
- 实际业务场景更为复杂,该方式也可用于多语言等场景
- 已知所有常量名称均存在
- 因常量数量较多,不想使用switch语句逐个调用
内容的提问来源于stack exchange,提问作者galalem
相关产品推荐
相关产品推荐

