为什么Typescript在使用[key in Enum]索引签名时不将枚举成员识别为有效属性
发布时间:2022-05-07 05:44:33 246
相关标签:
我正在开发一个 TypeScript 项目,在使用枚举成员作为接口的索引键时遇到了一个奇怪的问题。我的枚举和接口都在全局 .d.ts 文件中声明(没有导入或导出)。
// enums.d.ts
...
enum ItemFlag {
IsPushable = "isPushable",
IsTakable = "isTakable",
IsUnique = "isUnique"
}
...
// interfaces.d.ts
...
interface IThingProps {
id: string;
name: string;
}
interface IItemProps extends IThingProps {
[key in ItemFlag]?: boolean;
}
...
然而,当我试图创建一个实现IItemProps
接口:
const props: IItemProps = {
id: "item_small_cup",
name: "small cup",
[ItemFlag.IsTakable]: true
};
我得到以下错误:
&引用;键入“{id:string;name:string;isTakable:boolean;}”不可分配给类型“IItemProps”。Object literal只能指定已知的属性,并且类型“IItemProps”中不存在“[ItemFlag.IsTakable]”&引用;
奇怪的是,我用另一个枚举来做这件事,它工作得很好。唯一的区别是,我使用它内联声明对象的类型,比如:
const genders: {[key in Gender]: Pronouns; } = {
[Gender.It]: {
they: "it",
them: "it",
// You get the idea
}
}
我想这个例子也没有可选属性,但是删除了可选的“?”从索引签名ItemFlag
根本不会改变错误。
对这种奇怪的、不一致的行为有什么见解吗?
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报