控制流不使用联合元组进行类型缩小?

Control flow not type-narrowing with union tuple?

我对元组有疑问:

export async function redirectIf(
  nextCookies: NextApiRequestCookies,
  options: { notAuth: PagePath },
): Promise<[Redirect, undefined] | [undefined, UserDto]>;

如果 redirect 不存在,则不知道 user 存在:

Playground

感谢 TypeScript Community discord 服务器上的 Gerrit0#7591 回答:


TypeScript 不会跟踪跨单独变量的缩小。如果你有:

const x: [true, string] | [false, Error] = ...

并检查元组的第一个元素,然后TS可以缩小类型:

if (x[0]) {
  // TS knows x[1] is a string
}

但是如果你先解构,那么你有两个(据 TS 所知)完全不相关的变量。

const [isStr, val] = x
if (isStr) {
   // val is string | Error, not string
}

除了不解构,或者在充分缩小类型后进行解构之外,没有真正的解决方法。

if (x[0]) {
  const val = x[1] // val: string
}