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

如何在TypeScript中正确获取接口中特定键类型的所有属性?

获取接口中字符串键对应的属性类型

你尝试用数组typeof MyArray[number]的思路处理接口时遇到报错,原因是接口A没有定义字符串索引签名,只有明确声明的属性,所以A[string]无法直接生效。要获取键类型为string的所有属性类型,可以通过以下方式实现:

方法1:先筛选字符串键,再取对应类型

interface A {
  a: number;
  b: string;
  123: boolean; // 包含数字键的示例
}

// 提取A中所有字符串类型的键
type StringKeys = keyof A extends string ? keyof A : never;
// 获取这些字符串键对应的属性类型联合
type StringKeyProperties = A[StringKeys];
// StringKeyProperties 类型为 number | string

方法2:简洁的条件类型写法

通过映射类型筛选后直接提取:

interface A {
  a: number;
  b: string;
  123: boolean;
}

type StringKeyProperties = {
  [K in keyof A]: K extends string ? A[K] : never
}[keyof A];
// 结果同样是 number | string

特殊情况:接口有字符串索引签名

如果接口本身定义了字符串索引签名,比如:

interface A {
  [key: string]: number;
  a: number;
  b: number;
}

此时A[string]会直接返回索引签名定义的类型number,无需额外处理。

内容的提问来源于stack exchange,提问作者NeoZoom.lua

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 19:47:17