typescript - 我可以根据类型定义接口吗?
问题描述
如何根据类型定义带有键的接口?例如:
type FruitTypes = "bananna" | "appple " | "orange";
interface FruitInterface {
[key: string]: any; // key FruitTypes instead of string
}
// Expected result:
const FruitsObject: FruitInterface = {
bananna: "Bannana",
apple: "Apple",
orange: "Orange",
mango: "Mango" // Error
};
我试过这样的事情:
interface FruitInterface {
[key: keyof FruitTypes]: any;
}
也许还有另一种方法吗?
提前致谢。
解决方案
这就像您希望的那样:
const FruitsObject: Record<FruitTypes, any>
您需要接口是否有特定原因?这也是可能的:
interface FruitInterface extends Record<FruitTypes, any> {}
const FruitsObject: FruitInterface
推荐阅读
- r - 如何将文本添加到图形的节点中?
- r - 在浏览器选项卡中更改 plotly html 绘图标题
- entity-framework-core - 实体存在时 SingleOrDefault 返回 null
- r - 如何配置批处理脚本以使用 future.batchtools (SLURM) 并行化 R 脚本
- matlab - 如何从文本文件中读取列并相应地存储它们?
- jquery - 图像放大 object-fit:覆盖压缩图像
- javascript - 在 2 个屏幕上显示 2 个组件并同步它们
- python - 通过 Pyspark 查询一行 JSON 文件
- javascript - React-Native Flat List RenderList 问题
- javascript - GraphQL 不允许在 NodeJS 中插入数组对象