你好,Stackoverflow 的人,
我正在尝试创建一个函数来防止代码在运行时执行,并且存在不正确的流类型。
我的理解是,在运行时执行此操作的方法是改进或检查类型是否与所需内容匹配,并使用 Flow 来密切注意在此过程中不会遗漏任何案例。
一个简单的情况是我有一个字符串输入,我想确认匹配枚举/联合类型。我可以按照我对文字的期望进行此工作,例如
/* @flow */
type typeFooOrBaa = "foo"| "baa"
const catchType = (toCheck: string): void => {
// Working check
if (toCheck === "foo" || toCheck === "baa") {
// No Flow errors
const checkedValue: typeFooOrBaa = toCheck
// ... do something with the checkedValue
}
};
在这里试试
自然,我想避免嵌入文字。
我尝试过的一件事是等效的对象键测试,它不起作用:-( 例如
/* @flow */
type typeFooOrBaa = "foo"| "baa"
const fooOrBaaObj = {"foo": 1, "baa": 2}
const catchType = (toCheck: string): void => {
// Non working check
if (fooOrBaaObj[toCheck]) {
/*
The next assignment generates the following Flow error
Cannot assign `toCheck` to `checkedVariable` because: Either string [1] is incompatible
with string literal `foo` [2]. Or string [1] is incompatible with string literal `baa` [3].",
"type"
*/
const checkedVariable: typeFooOrBaa = toCheck
}
};
在这里试试
是否有可能在不必走完整的流程运行时路线的情况下实现这样的目标?如果是这样,最好怎么做?
谢谢你的帮助。