【发布时间】:2022-06-11 16:34:18
【问题描述】:
我有一个环境变量作为字符串进入我的应用程序,并构建了一个配置方法来验证和返回基于枚举键(来自字符串)的枚举值:
import { LedMatrix, RowAddressType, MuxType } from 'rpi-led-matrix'
// Validate and return valid MatrixOptions.rowAddressType
export const configRowAddressType = (
configRowAddressType?: string,
): RowAddressType => {
if (!configRowAddressType) {
return LedMatrix.defaultMatrixOptions().rowAddressType
}
const rowAddressType = configRowAddressType as keyof typeof RowAddressType
const keys = Object.keys(RowAddressType)
if (keys.includes(rowAddressType)) {
return RowAddressType[rowAddressType]
}
if (rowAddressType) {
console.error(
`supplied rowAddressType key of ${rowAddressType} is not a valid option, assigning default of ${
LedMatrix.defaultMatrixOptions().rowAddressType
}.`,
)
}
return LedMatrix.defaultMatrixOptions().rowAddressType
}
它有效。但是,我有另一种看起来非常相似的方法,它验证并键入另一个表示另一个枚举键的变量:
// Validate and return valid MatrixOptions.multiplexing
export const configMultiplexing = (configMultiplexing?: string): MuxType => {
if (!configMultiplexing) {
return LedMatrix.defaultMatrixOptions().multiplexing
}
const multiplexing = configMultiplexing as keyof typeof MuxType
const keys = Object.keys(MuxType)
if (keys.includes(multiplexing)) {
return MuxType[multiplexing]
}
if (multiplexing) {
console.error(
`supplied multiplexing key of ${multiplexing} is not a valid option, assigning default of ${
LedMatrix.defaultMatrixOptions().multiplexing
}.`,
)
}
return LedMatrix.defaultMatrixOptions().multiplexing
}
我将总共有五种左右这些类似的方法。这似乎是多余的,但我正在努力解决如何返回动态枚举类型。这是一个可以工作的粗略示例,可能并不理想:
export const configEnumValueByKey = (inputValue: string, enumType: RowAddressType | MuxType | SomethingElse | AnotherSomething | MoreSomething | YetAnother): RowAddressType | MuxType | SomethingElse | AnotherSomething | MoreSomething | YetAnother => {
// ...
}
有没有一种方法可以重构处理动态设置返回类型的单个方法?
【问题讨论】:
-
LedMatrix.defaultMatrixOptions()的返回类型是什么? -
LedMatrix.defaultMatrixOptions()类型为MatrixOptions。 -
那么
RowAddressType/MuxType的类型是什么?是Record还是别的什么? -
这些是枚举:
export declare enum RowAddressType { /** * Corresponds to direct setting of the row. */ Direct = 0, /** * Used for panels that only have A/B. (typically some 64x64 panels) */ AB = 1, /** * Direct row select */ DirectRow = 2, /** * ABC addressed panels */ ABC = 3, /** * 4 = ABC Shift + DE direct */ ABCShift = 4 } -
export declare enum MuxType { Direct = 0, Stripe = 1, Checker = 2, Spiral = 3, ZStripe = 4, ZnMirrorZStripe = 5, Coreman = 6, Kaler2Scan = 7, }
标签: typescript