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

如何定义无固定键的多层嵌套全字符串值对象的TypeScript类型?

如何定义任意层级嵌套、仅含字符串值的对象类型

你需要使用递归类型来解决这个问题,递归类型允许接口自身引用自己,从而支持任意层级的嵌套结构。

正确的类型定义

interface NestedStringObject {
  [key: string]: string | NestedStringObject;
}

这个接口明确了:对象的每个属性要么是string类型,要么是另一个符合NestedStringObject结构的嵌套对象,完全匹配你需要的多层嵌套字符串值对象。

为什么原接口无法满足需求

你之前的TestType使用string|object作为属性类型,存在两个核心问题:

  • object是泛指所有对象,TypeScript无法识别深层嵌套的对象也遵循TestType的结构,因此anotherNested这类深层嵌套的属性无法通过类型检查;
  • 当访问对象属性时,TypeScript只能推断属性值为string或object,无法确定具体类型,导致传入要求string的代码时触发类型错误。

类型安全地访问字符串值

如果需要确保访问的属性值是string类型,可以使用类型守卫函数实现类型推断:

function isString(value: string | NestedStringObject): value is string {
  return typeof value === 'string';
}

// 使用示例
const obj: NestedStringObject = {
  foo: "bar",
  foo2: "bar2",
  nestedFoo: {
    foo3: "bar3",
    anotherNested: {
      foo4: "bar4"
    }
  }
};

// 安全访问字符串值
if (isString(obj.nestedFoo.anotherNested.foo4)) {
  // 此处foo4被TypeScript推断为string类型
  console.log(obj.nestedFoo.anotherNested.foo4.toUpperCase());
}

如果能确定某个属性路径必然是字符串,也可以用类型断言快速处理:

const foo4 = obj.nestedFoo.anotherNested.foo4 as string;
// 此时foo4会被当作string类型使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 20:27:40