如何通过键数组获取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
相关产品推荐
相关产品推荐

