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

求支持对象单一路径描述的TypeScript类型(含数组处理)

需求:实现特定的TypeScript对象路径类型

需要实现一个TypeScript类型,能够将对象从根属性到任一叶子属性的路径描述为字符串数组,具备以下特性:

  • 对象结构通过interface/type定义
  • 仅支持单一路径,无分支
  • 允许在任意层级终止路径
  • 只能选择当前节点的直接子属性,不能选同级或祖先节点
  • 若属性为数组,支持通过PredicateFunction或数字索引选择特定元素,后续可基于数组元素类型继续路径(假设数组元素类型统一)
  • 类型检查时将可选属性视为必填,忽略其可选性
  • 支持智能提示,仅给出正确的自动补全建议
  • 针对大型对象/类型仍具备良好性能

该类型无需递归,可限制嵌套层级,超出后回退为any;允许使用复杂实现方案,只要功能可用。

示例代码

// 用于选择数组元素的断言函数类型
export type PredicateFunction<ArrayType> = (array: ArrayType, index?: number) => boolean;

interface State {
    city: {
        name: string;
        inhabitants: {
            firstname: string;
            lastname: string;
        }[],
        districts: string[]
    }
}

// 有效路径示例
const path1 = ['city'];
const path4 = ['city', 'name'];
const path2 = ['city', 'inhabitants'];
const path3 = ['city', 'inhabitants', 1];
const path5 = ['city', 'inhabitants', inhabitant => inhabitant.firstname === 'Max', 'lastname'];

// 无效路径示例
const invalidPath1 = ['name']; // 直接访问根节点不存在的属性
const invalidPath2 = ['city', 'inhabitants', 'firstname']; // 跳过数组索引/断言直接访问元素属性
const invalidPath3 = ['inhabitants', 1, 'firstname']; // 直接访问根节点不存在的属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 04:02:17