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

TypeScript如何为键是否在任意数组内的对象定义不同值类型

TypeScript 类型约束实现方案

不需要依赖提前定义的as const常量数组,通过泛型捕获入参的字面量类型+交叉类型约束,就能实现任意传入字符串数组的类型校验,改造后的完整代码如下:

function allFinished<T extends string>(
  pendingProps: T[],
  allProps: Record<T, { isFinished: boolean }> & Record<string, unknown>
): boolean {
  return pendingProps.every((pendingProp) => allProps[pendingProp].isFinished)
}

实现逻辑说明

  • 定义泛型参数<T extends string>,TS会自动从传入的pendingProps数组中提取所有字符串元素的字面量联合类型,不需要额外手动声明类型
  • 对allProps的类型约束通过交叉类型实现:
    • Record<T, { isFinished: boolean }>:所有存在于pendingProps数组中的键,对应的值必须包含布尔类型的isFinished属性,缺省或者类型不对都会直接抛出TS类型错误
    • Record<string, unknown>:所有不在pendingProps中的键,对应值可以是任意类型,不做额外限制

校验效果示例

// ✅ 正常通过校验
allFinished(
  ['task1', 'task2'],
  {
    task1: { isFinished: true },
    task2: { isFinished: false, remark: '处理中' }, // isFinished必填,支持额外属性
    otherConfig: '任意字符串值', // 非pendingProps内的键无类型限制
    randomNum: 999
  }
)

// ❌ TS抛出类型错误:task2缺少必填的isFinished属性
allFinished(
  ['task1', 'task2'],
  {
    task1: { isFinished: true },
    task2: { progress: 50 }
  }
)

这个实现同时兼容普通字符串数组、as const标记的常量元组两种传参方式,不需要针对常量数组做特殊适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 15:33:21