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

如何通过键数组获取TypeScript嵌套对象的值并验证存在性

验证嵌套颜色对象中的路径是否存在

先看定义的类型和颜色对象:

interface Colors {
  [key: string]: Colors | string
}

const colors: Colors = {
  light: {
    gray: '#aaa',
  },
  black: '#000',
}

需求是验证传入的字符串(比如'light-gray')是否对应colors里的某个颜色路径。已经把字符串分割成了键数组['light', 'gray'],但直接用keys.every(key => key in colors)没法正确验证嵌套路径——因为gray是light的子属性,不在顶层对象里,所以这个方法会返回false。

验证路径是否存在

可以通过逐层遍历键数组,检查每一层的对象属性:

function isColorPathValid(keys: string[]): boolean {
  let current: Colors | string = colors;
  for (const key of keys) {
    // 当前不是对象的话,路径直接中断
    if (typeof current !== 'object' || current === null) {
      return false;
    }
    if (!(key in current)) {
      return false;
    }
    // 进入下一层对象继续检查
    current = current[key];
  }
  // 最后必须是颜色字符串(如果不需要严格验证是颜色值,可去掉这行)
  return typeof current === 'string';
}

// 测试示例
const color = 'light-gray';
const keys = color.split('-');
console.log(isColorPathValid(keys)); // 输出: true
console.log(isColorPathValid(['light', 'red'])); // 输出: false
console.log(isColorPathValid(['white'])); // 输出: false

获取路径对应的颜色值

如果需要同时拿到对应的颜色值,可以用这个函数:

function getColorByPath(keys: string[]): string | null {
  let current: Colors | string = colors;
  for (const key of keys) {
    if (typeof current !== 'object' || current === null || !(key in current)) {
      return null;
    }
    current = current[key];
  }
  return typeof current === 'string' ? current : null;
}

// 测试示例
console.log(getColorByPath(keys)); // 输出: '#aaa'
console.log(getColorByPath(['black'])); // 输出: '#000'
console.log(getColorByPath(['light', 'blue'])); // 输出: null

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 23:05:13