如何通过布尔值输入guard?

问题描述

我有以下内容:

exampleFunction = (param: string) => {
  try {
    const result = processString(param) as { resultExample: string };
    
    return { isSuccess: true,...result };
  catch (error) {
    return { isSuccess: false };
  }
}

理想情况下,返回值的类型为:{ isSuccess: true,resultExample: string} | { isSuccess: false },但其类型为{ isSuccess: boolean,resultExample: string } | { isSuccess: boolean },这令人沮丧,因为这意味着我无法利用类型保护。

const data = exampleFunction("exampleParam");

if (data.isSuccess) {
  functionExpectingResultExample(data.resultExample); // Type Error because "resultExample: string | {}" is not assignable to "resultExample: string"
}

以上内容不应出错,因为应将true和false用作类型保护,而应将它们键入为布尔值。

我唯一的手动输入为true和false的解决方案吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)