在处理类型类型时,我有一个关于转换的问题。我有以下类型:
export type DataChampLogLevel = 'debug' | 'verbose' | 'info' | 'warning' | 'error'不,一些记录器只接受debug,而另一些则期望verbose
我有一个日志门面,它期望DataChampLoglevel
export interface DataChampLogger {
setLogLevel(level: DataChampLogLevel): void
}
//implementation
setLogLevel(level: DataChampLogLevel): void {
SomeLogger.setLogLevel(level) // compiler type error debug is not allowed in type OtherLogLevel..
}在内部,我需要将值从(例如debug )转换为verbose,而编写转换函数相当简单,我想知道类型write类型(例如字符串、模板等)是否也可以这样做。我玩了一会儿,但没能想出正确的解决办法。(这只是我自己提高技能的好奇心;)
马蒂亚斯
发布于 2022-02-11 10:24:46
我在想,类型types类型是否也能做到这一点?
不是的。您所描述的是运行时值转换。TypeScript类型在运行时不存在(除了枚举周围的一个小警告)。因此,对此没有TypeScript类型的解决方案。您将需要一个运行时解决方案来修改运行时值。
这可能也可能没有类型方面,因为SomeLogger.setLogLevel似乎接受与DataChampLogLevel不同的类型,因此您需要一种方法来告诉TypeScript,SomeLogger.setLogLevel允许(更新的)值。但它无法帮助它的运行时方面。
例如,假设SomeLogger.setLogLevel接受一个SomeLoggerLogLevel,即:
type SomeLoggerLogLevel = 'verbose' | 'info' | 'warning' | 'error';在这种情况下,没有必要对类型做任何明确的操作,因为类型记录的流分析可以看到您在执行以下操作时可以内联地处理它:
setLogLevel(level: DataChampLogLevel): void {
if (level === "debug") {
level = "verbose";
}
SomeLogger.setLogLevel(level);
}但是,如果您以另一种方式(如查找表)这样做,您可能需要向TypeScript保证您的运行时转换是正确的。例如,TypeScript不会对此感到满意:
const logLevelMap: Partial<Record<DataChampLogLevel, SomeLoggerLogLevel>> = {
debug: "verbose",
};
const obj: DataChampLogger = {
setLogLevel(level: DataChampLogLevel): void {
level = logLevelMap[level] ?? level;
SomeLogger.setLogLevel(level); // Argument of type 'DataChampLogLevel' is not assignable to parameter of type 'SomeLoggerLogLevel'.
}
};但是,如果您添加了一个类型断言函数,那么它是愉快的:
const logLevelMap: Partial<Record<DataChampLogLevel, SomeLoggerLogLevel>> = {
debug: "verbose",
};
function assertsIsValidSomeLoggerLogLevel(level: DataChampLogLevel): asserts level is SomeLoggerLogLevel {
if (level in logLevelMap) {
throw new Error(`Invalid SomeLoggerLogLevel "${level}"`);
}
}
const obj: DataChampLogger = {
setLogLevel(level: DataChampLogLevel): void {
level = logLevelMap[level] ?? level;
assertsIsValidSomeLoggerLogLevel(level);
SomeLogger.setLogLevel(level);
}
};https://stackoverflow.com/questions/71078427
复制相似问题