typescript - 对于给定的字典,允许其键的子集获得与更广泛的其余键不同的值
问题描述
使用给定的Record<string, SomeInterface>
字典,我想要一个可以从值中省略特定道具的“特殊”键的联合
这是对不幸不起作用的实现的直观尝试:
export type Dictionary<K extends keyof any, V> = Partial<Record<K, V>>
interface Foo { x: string }
interface Bar { x: string, y: number }
type FooKeys = 'foo1' | 'foo2'
type MixedDictionary = Dictionary<string, Bar> & Dictionary<FooKeys, Foo>
const mixedDictionary: MixedDictionary = {
"foo1": { x: "some string" },
"sfdds": { x: "some string", y: 23 }
}
给我错误:
Type '{ foo1: { x: string; }; sfdds: { x: string; y: number; }; }' is not assignable to type 'MixedDictionary'.
Type '{ foo1: { x: string; }; sfdds: { x: string; y: number; }; }' is not assignable to type 'Partial<Record<string, Bar>>'.
Property '"foo1"' is incompatible with index signature.
Property 'y' is missing in type '{ x: string; }' but required in type 'Bar'.(2322)
我期待{ "foo1": { x: "some string" }}
可以分配给MixedDictionary
,因为它可以分配给Dictionary<FooKeys, Foo>
,但不知何故这还不够。
有没有一种直接的方法来实现我的用例?
解决方案
推荐阅读
- android - 如何使按钮上的点击动作可见?
- react-native - 如何在 React Navigation 中为静态 navigationOptions 创建组件?
- python - Django 构建查询的最佳方法是什么
- mysql - 使用 OR 进行查询,使查询执行缓慢
- symfony - 教义继承、基类和两个子类型
- r - R Shinydashboard 删除图形周围的空白边框
- python - 如何在 spyder 中获取 ipython 控制台以打印全文?
- node.js - 使用 Mongoose 在 MongoDB 中存储可变长度数组
- react-native - 为什么 backgroundColor 不适用于 React Native 中的 View?
- html - 在 Sublime 中使用 * 或变量搜索