【问题标题】:TypeScript type check inline isn't the same as type check in functionsTypeScript 内联类型检查与函数中的类型检查不同
【发布时间】:2020-02-20 16:03:18
【问题描述】:

我有一个奇怪的(至少对我而言)问题,即内联类型检查的工作方式与函数中的类型检查不同。提取到函数时,完全相同的检查不起作用。

我已经发布了一个屏幕截图,以便您查看错误,以及一个link to same code on Code Sandbox

我首先在 IntelliJ 中遇到了这个问题,但在 CodeSandbox(Visual Studio Code)中提出了这个孤立的问题,所以我猜这个问题是 TypeScript。

你知道为什么会这样吗?

【问题讨论】:

    标签: typescript types


    【解决方案1】:

    那是因为你需要实现一个“类型保护”:

    const isPromise = (maybePromise: unknown): maybePromise is Promise<unknown> => {
      return (
        typeof maybePromise === "object" &&
        typeof (maybePromise as Promise<unknown>).then === "function"
      );
    };
    
    // Util to tell if argument is a String
    const isString = (maybeString: unknown): maybeString is string => {
      return typeof maybeString === "string";
    };
    

    maybePromise is Promise&lt;unknown&gt;maybeString is string will guarantee the type in the scope.

    这是一个工作示例:https://stackblitz.com/edit/typescript-8ilugj

    【讨论】:

    • 太棒了。不知道那个。谢谢。
    猜你喜欢
    • 2020-10-26
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 2020-08-04
    • 2021-11-14
    • 2020-04-14
    相关资源
    最近更新 更多