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

TypeScript中如何访问接口的动态属性类型

获取TypeScript接口索引签名的值类型

你用Person[keyof typeof Person]无效是因为typeof Person用错了——Person是类型而非运行时的值,typeof只能用来获取值的类型,不能直接套在接口类型上。

正确的实现方式有两种:

  1. 直接通过索引签名的键类型取值
    你的接口使用string类型的索引签名,直接写Person[string]就能拿到对应的值类型:

    type PersonValue = Person[string];
    // PersonValue 等价于 { name: string; alias: string; active: string[]; values: string[]; }
    
  2. 用keyof获取接口键类型后取值
    对于带字符串索引签名的接口,keyof Person等价于string | number(TS中数字键会自动转为字符串),因此也可以这么写:

    type PersonValue = Person[keyof Person];
    

    这个写法和第一种结果完全一致,如果之前这么写没生效,大概率是代码拼写或其他逻辑问题导致的。

另外,如果你想让代码更清晰易维护,也可以把值类型单独抽出来定义,后续直接复用:

export type PersonInfo = {
  name: string;
  alias: string;
  active: string[];
  values: string[];
};

export interface Person {
  [key: string]: PersonInfo;
}

// 直接复用已定义的PersonInfo即可
type PersonValue = PersonInfo;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:18:50