如何限制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
相关产品推荐
相关产品推荐

