You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于分支收窄的模块级常量批量收窄TypeScript多变量类型?

基于共享常量批量收窄TypeScript类型的高效方案

我尝试通过分支中收窄的模块级常量来同时收窄多个元素的TypeScript类型,但发现TypeScript仅支持两种实现方式:要么为每个元素单独使用谓词函数,要么在特定分支内将其标注为条件类型。

我试过品牌类型(branded types)、条件类型,但似乎都必须逐个收窄类型,这在我的使用场景中不够便捷。有没有方法可以提示TypeScript利用这些类型之间的关联?

品牌类型与类型谓词示例

const condition = Math.random() > 0.5;

type onlyTrue<T> = T & { brand: "true" };
type onlyFalse<T> = T & { brand: "false" };

const a: onlyTrue<number> = 123 as any;
const b: onlyFalse<string> = "abc" as any;
const u = condition ? a : b;
const u2 = condition ? a : b;

type NarrowTrue<T> = Extract<T, onlyTrue<any>>;

function trueBranch(x: any): x is NarrowTrue<typeof a> {
  return condition;
}

if (trueBranch(u)) {
  u;
  u2; // 未被收窄
}

if (condition) {
  u; // 未被收窄
  u2; // 未被收窄
}

条件类型示例

const condition = Math.random() > 0.5;

type ConditionalType<X> = X extends true ? number : string;

function conditional<X>(value: any) {
  return value as X extends true ? number:string
}

const u = conditional<typeof condition>(condition? 1 : "a")
const t = (condition ? 1 : "a") as ConditionalType<typeof condition>;;

if (condition) {
  t; u; // 未被收窄
  const t2 = condition ? 1 : "a"; // 未被收窄

  // 如果把条件判断延迟到if分支内,TS能正确收窄类型
  const u3 = conditional<typeof condition>(condition? 1 : "a")
  const t3 = (condition ? 1 : "a") as ConditionalType<typeof condition>;;
}

我正在寻找一种更高效的方式,基于单个共享常量批量收窄多个类型,是否有我未考虑到的方案?


内容的提问来源于stack exchange,提问作者doublethinker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 13:32:19