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

如何在TypeScript中提取接口指定键的类型?

TypeScript 从已有接口提取特定键的类型实现方法

完全可以实现,你可以用TypeScript的索引类型查询语法直接从已定义的接口中提取特定键对应的类型,不用重复定义。

针对你的示例代码,只需要把PooProps里的wantType类型改成Props['certainType']即可:

interface Props {
  aType: number;
  bType: string;
  certainType: 'a' | 'b' | 'c';
}

interface PooProps {
  cType: boolean;
  wantType: Props['certainType']; // 直接提取Props中certainType的类型
}

function foo(value: PooProps){}

const result = foo({cType: true, wantType: 'a'}) // 类型校验正常
const errorResult = foo({cType: true, wantType: 'd'}) // 会触发类型错误,符合预期

补充说明

  • 这种语法的核心是Type['Key'],它会直接返回Type接口中Key对应的类型,后续如果Props里的certainType类型发生变更,wantType的类型会自动同步,避免重复维护的麻烦。
  • 如果需要提取多个键对应的类型,可以使用Pick工具类型,比如Pick<Props, 'aType' | 'certainType'>,它会生成一个包含指定键的新类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 15:22:01