AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79048935
Accepted
dwjohnston
dwjohnston
Asked: 2024-10-03 10:14:24 +0800 CST2024-10-03 10:14:24 +0800 CST 2024-10-03 10:14:24 +0800 CST

我可以让 TypeScript 类型保护针对函数重载的结果应用吗?

  • 772

我有一些如下所示的代码:

type UserTypes = "user" | "super-user" | "admin"  ;


function getUserType() : UserTypes {

}

function getAdminPrivs(userType: "user" | "super-user") : null  
function getAdminPrivs(userType: "admin") :  string 
// nb. we need to double declare the final line
// see: https://stackoverflow.com/questions/70146081/why-does-an-overloaded-function-declaration-sometimes-force-useless-type-narrowi
function getAdminPrivs(userType: UserTypes) : null | string
function getAdminPrivs(userType: UserTypes) : null | string {

  if(userType === "admin"){
    return "hello"
  }

  return null; 
}


// "user" | "super-user" | "admin"
const userType = getUserType();

// string| null  
const result = getAdminPrivs(userType);


if(userType === "user" || userType === "super-user"){

}
else {
  // string | null 
  // I really want this to be just string
  result
}

在这里,我希望 TypeScriptresult通过检查 的类型来缩小 的类型userType。这可能吗?

举个例子,如果我稍微变换一下代码:

const userType = getUserType();
if(userType === "user" || userType === "super-user"){
  // null
  const result = getAdminPrivs(userType);
}
else {
  //string 
  const result = getAdminPrivs(userType);
}

这在语义上是类似的,但是我们获得了类型缩小的优势。(我无法在实际用例中使用这种技术,因为它getAdminPrivs实际上是一个 React hook,并且不允许有条件地调用 React hook)

typescript
  • 1 1 个回答
  • 29 Views

1 个回答

  • Voted
  1. Best Answer
    jcalz
    2024-10-03T11:15:01+08:002024-10-03T11:15:01+08:00

    TypeScript 的缩小功能仅在明确编程到类型检查器中的特定情况下有效。它的控制流分析相当强大,但只能在“向前”方向上工作。也就是说,给定的检查可以缩小检查后其余范围的值,但不能返回并重新解释先前分析的代码。除了最简单的程序外,这对于所有程序来说都非常糟糕。例如

    const userType = getUserType();
    if(userType === "user" || userType === "super-user"){
      const result = getAdminPrivs(userType); // null
    }
    else {
      const result = getAdminPrivs(userType); //string 
    }
    

    之所以有效,是因为userType可以缩小,并且随后的使用userType反映了这种缩小。但是

    const userType = getUserType();
    const result = getAdminPrivs(userType);
    if(userType === "user" || userType === "super-user"){
      result; // want null, but still string | null
    }
    else {
      result; // want string, but still string | null
    }
    

    在 TypeScript 中不可能工作,因为它必须缩小范围userType,然后在所有先前的语句中追溯缩小范围userType,然后重新分析的返回类型getAdminPrivs,并重新分析的类型result。人类很容易进行这样的分析,因为你知道你在寻找什么。但想象一下,编译器需要付出多少努力来分析一个任意程序,其中对任何值的每次检查都会影响整个程序中该值的类型,这会影响依赖于该值的任何东西的类型,这会影响依赖于这些值的任何事物的类型,等等。

    这基本上无法以任何可扩展的方式实现,所以这是 TypeScript 的一个根本限制。


    有关此限制的来源,请参阅microsoft/TypeScript#41926,其中TS 团队开发负责人表示

    控制流缩小的工作原理是寻找适用于相关变量的语法。在此示例中,似乎没有任何东西直接影响 [ result] ,因此它具有未缩小的类型。

    我们没有足够的性能预算来进行正确检测这种模式所需的整个宇宙反事实分析。

    另请参阅microsoft/TypeScript#56221 上的类似评论:

    缩小范围的工作原理是形成可能影响变量类型的事物的控制流图,并检查这些事物以查看它们是否是看起来可能导致某些事物缩小的语法形式。它不是约束求解器样式的东西,无法处理各种其他逻辑运算符的组合和排列,因此如果您的逻辑依赖于某种反事实归纳,那么它不会被缩小范围所发现。值得庆幸的是,在大多数情况下,这通常与更易读的代码相对应。

    最后一点本质上是说,如果你编写了 TS 无法分析的代码,那么对于人类来说可能也会更难,如果你重写它(例如,通过由于 React hook 限制而无法编写的冗余形式),人类和 TS 都会更高兴。

    我不知道以下内容是否适用于您的用例,但您可以将其重新打包为判别联合userType的判别属性,如下所示:

    type TypeAndPrivs =
      { userType: "user" | "super-user", adminPrivs: null } |
      { userType: "admin", adminPrivs: string }
    function getTypeAndAdminPrivs(userType: UserTypes): TypeAndPrivs {
      return (userType === "admin") ? { userType, adminPrivs: "hello" } : { userType, adminPrivs: null }
    }
    

    然后,您可以对其进行解构,并使用结果为您提供预期的分析:

    const { userType, adminPrivs: result } = getTypeAndAdminPrivs(getUserType());
    if (userType === "user" || userType === "super-user") {
      result; // null
    }
    else {
      result; // string
    }
    

    是的,这仍然有点多余,但至少你没有getAdminPrivs()多次调用。

    游乐场链接到代码

    • 1

相关问题

  • 为什么我们在条件语句中使用方括号“[]”?

  • Nestjs有关模块的问题

  • 如何获取文件的打字稿元数据?

  • 如何将数组转换为像这样的对象返回 const 类型?

  • “没有重载匹配”我的 Object.assign() 调用;我该如何修复它?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve