typescript - Typescript — 确保对象 prop 键与 prop 值相同
问题描述
我需要输入以下对象结构:
const entities = {
abc: {
id: 'abc'
},
def: {
id: 'def'
}
}
每个对象的 prop 键都需要匹配其对应的id
.
我试过这样做:
interface EntitiesMap<E extends Entity> {
[K in E['id']]: E;
}
interface Entity {
id: string;
}
但这并不能确保 prop 键和id
值匹配。例如:
const entities = {
ghi: {
id: 'aaaaa' // should throw an error as ghi doesn't match aaaaa
}
}
有什么想法可以让我完成这项工作吗?
解决方案
那是因为您定义id
为string
and'aaaaa'
是一个字符串。你可以使用这样的东西,id
它比以下步骤更具体string
:
type IdType = keyof typeof entities // "abc" | "def"
// and use it as id type
interface Entity {
id: IdType
}
这可能不是您正在寻找的确切答案,但这是一个好的开始。希望它会有所帮助
推荐阅读
- c# - 使用中间表删除级联
- .net - 如何在 VS2019 中调试挂起的单元测试运行会话
- javascript - 计算数组中元素的平均值
- java - 为什么我的适配器在调用 firebase 方法时会重新启动?
- php - 由于自定义 wordpress 短代码,JSON 响应无效
- sql - SQL如何计算从日期开始的记录
- alexa - Amazon Alexa Skills - 如何在技能中添加循环?
- php - 如何在wordpress管理前端显示这样的吐司
- javascript - 如何删除此按钮的此图形错误?
- asp.net - 当我单击确认按钮时,我想打开一个弹出窗口并确认“您确定”、“是”、“否”。我该怎么做?