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

TypeScript如何将函数参数类型指定为接口的属性类型?

TypeScript接口相关类型问题解答

1. 能否将变量类型指定为接口的键之一?

当然可以,TypeScript提供了keyof操作符,它能提取接口的所有键名组成联合类型,用这个类型就能约束变量只能是接口的键之一。

以你提供的IExample为例:

interface IExample {
  a: string;
  b: {
    b1: string;
    b2: string | number | boolean;
  };
}

// 提取IExample的所有键,得到联合类型 'a' | 'b'
type ExampleKeys = keyof IExample;

// 变量k只能是'a'或'b'
const k: ExampleKeys = 'a'; // 合法
// const k: ExampleKeys = 'c'; // 报错:类型'"c"'不能赋值给类型'"a" | "b"'

2. 如何将函数参数类型定义为接口的某个属性的类型?

你之前用IExample.b的写法是错误的,TypeScript中访问接口的属性类型需要使用索引访问类型,语法为接口名['属性名']。

针对你的需求,正确写法如下:

interface IExample {
  a: string;
  b: {
    b1: string;
    b2: string | number | boolean;
  };
}

// 直接用IExample['b']作为参数类型,无需额外定义接口
const foo = (arg: IExample['b']): void => {
  console.log(arg.b1, arg.b2);
};

// 测试:传入符合类型的参数
foo({ b1: 'test', b2: 123 }); // 合法
foo({ b1: 'test', b2: true }); // 合法

这种索引访问类型还支持嵌套属性,比如想直接用b2的类型,可以写IExample['b']['b2'],它会解析为string | number | boolean。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:35:45