【问题标题】:Typescript treats boolean like true | false when strictNullCheck is offTypescript 将布尔值视为 true |当 strictNullCheck 关闭时为 false
【发布时间】:2020-02-20 23:06:56
【问题描述】:

我有以下打字稿代码:

type PossiblePromise<T> = T extends Promise<infer U>
  ? T | U
  : T | Promise<T>;
type Z = PossiblePromise<boolean>;

const a = "a"
const f: () => Z = () => Promise.resolve(!!a);

strictNullChecks 设置为 false。

结果类型Zboolean | Promise&lt;false&gt; | Promise&lt;true&gt;,但我希望它是boolean | Promise&lt;boolean&gt;。所以最后一行产生了一个错误:

Type 'Promise<boolean>' is not assignable to type 'boolean | Promise<false> | Promise<true>'.
  Type 'Promise<boolean>' is not assignable to type 'Promise<false>'.
    Type 'boolean' is not assignable to type 'false'.(2322)
input.ts(7, 10): The expected type comes from the return type of this signature.

关于为什么 typescript 表现得像这样将 boolean 视为 true | false 的任何想法,这不应该是关闭 strictNullChecks 的情况。

如何实现PossiblePromise&lt;T&gt; 类型与布尔值正确配合?

https://www.typescriptlang.org/play/?strictNullChecks=false&ssl=6&ssc=1&pln=7&pc=47#code/C4TwDgpgBACg9gZwQSwEYBsIwE5wLbIIQA8AKgHxQC8UpUEAHsBAHYAmCsuBRxyLAMwjYoAVXIBYAFBQoAflpQAPmOmyAXIpU58hEhQDc00JCgAtarEQoMWbnuKo4cTAEMW5I1OkBjOCwRgKFdLACJXUN9-QKgBTQAKAEpqSgsaJJSuXSIAOmwIBBcANwh4gEIy10SDIA

【问题讨论】:

  • 据我所知,boolean 在 TypeScript 中被实现为等效于 true | false 的联合,无论 --strictNullChecks 是打开还是关闭;你有什么特别的原因吗?

标签: typescript boolean


【解决方案1】:

您可以通过解除 Promise 类型来修复它。问题是boolean 是联合类型,而条件类型自动为distributed over union types。考虑以下代码:

type PossiblePromise<T, Y = Promise<T>> = T extends Promise<infer U>
  ? T | U
  : T | Y;
type Z = PossiblePromise<boolean>;

const a = "a"
const f: () => Z = () => Promise.resolve(!!a);

如您所见,Y 被提升到条件类型之外,仅在需要时使用。

顺便说一句 - 使用 Boolean 不是您的类型定义的修复,它只是与您的实现配合良好的不同类型(布尔不是联合类型)- 考虑更多关于 Boolean 的信息。这也意味着如果您使用任何其他联合类型,它会产生相同的错误效果,请检查下面的差异

type T = "a" | "b";
// previous result type would be:
type PreviousResult = "a" | "b" | Promise<"a"> | Promise<"b">
// after the change it will be:
type Result = "a" | "b" | Promise<"a" | "b">

【讨论】:

    【解决方案2】:
    type Z = PossiblePromise<Boolean>;
    

    【讨论】:

    • 你能解释一下吗?
    • 我是 Angular 的新手,但它希望您在这里定义一个类类型,其中 Boolean 是类类型。需要另一个来更好地解释这一点。
    • 我能想到的最好方法是你告诉它期待一个布尔类型值,而如果你指定布尔值,它将是一个值而不是一个值类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 2018-08-17
    • 2011-12-28
    • 2011-04-27
    • 1970-01-01
    相关资源
    最近更新 更多