【发布时间】: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。
结果类型Z 是boolean | Promise<false> | Promise<true>,但我希望它是boolean | Promise<boolean>。所以最后一行产生了一个错误:
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<T> 类型与布尔值正确配合?
【问题讨论】:
-
据我所知,
boolean在 TypeScript 中被实现为等效于true | false的联合,无论--strictNullChecks是打开还是关闭;你有什么特别的原因吗?
标签: typescript boolean