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

如何限制TypeScript对象中属性类型为同对象指定属性名?

可行,用TypeScript的keyof操作符就能实现

你可以通过以下两种方式实现这个需求,核心是利用keyof操作符提取目标属性的名称组成联合类型:

方法一:拆分基础类型

先定义不含current的基础属性类型,再用keyof获取它的键类型:

type BaseProps = {
  one: string;
  two: string;
  three: string;
};

interface A extends BaseProps {
  current: keyof BaseProps; // 类型自动推导为 "one" | "two" | "three"
}

方法二:直接在接口内处理

通过Omit排除current自身,再用keyof提取剩余属性的键:

interface A {
  one: string;
  two: string;
  three: string;
  current: keyof Omit<A, 'current'>;
}

这样定义后,current只能被赋值为"one"、"two"或"three"中的一个,赋值其他字符串时TypeScript会直接抛出类型错误,完美替代宽泛的string类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 17:12:24