【问题标题】:How to type guard via booleans?如何通过布尔值输入守卫?
【发布时间】:2020-12-31 21:10:16
【问题描述】:

我有以下几点:

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 应用作类型保护,而是将它们键入为布尔值。

我唯一的解决方案是手动输入真假吗?

【问题讨论】:

    标签: typescript typeguards


    【解决方案1】:

    您需要将 isSuccess 返回类型转换为 const,以便 TypeScript 知道该值不是布尔值,而是特定的、不变的布尔值:

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

    查看proof-of-concept on TypeScript Playground


    如果您愿意,也可以将整个返回的对象转换为 const:

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

    See the second proof-of-concept here.

    【讨论】:

    • 哇哦哦哦。魔法!我可以处理这个。如果我有很多这种范式....我可以做类似的事情:const TRUE = true as const 然后在不同的功能中,做 isSuccess: TRUE 并且它会自动为我输入它作为一个常量?
    • 刚刚检查过,是的,我可以:)。
    猜你喜欢
    • 2021-10-15
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 1970-01-01
    • 2017-05-08
    • 2017-11-07
    相关资源
    最近更新 更多