如何通过布尔值输入守卫?

How to type guard via booleans?

我有以下内容:

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

理想情况下,return 会键入:{ 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 应该被用作类型保护,但它们被输入为布尔值。

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

您需要将 isSuccess return 类型转换为 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


您也可以将整个 returned 对象转换为 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.