首页 > 解决方案 > 对于给定的字典,允许其键的子集获得与更广泛的其余键不同的值

问题描述

使用给定的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>,但不知何故这还不够。

有没有一种直接的方法来实现我的用例?

游乐场链接在这里

标签: typescriptdictionarytypescript-genericsunion-typesmapped-types

解决方案


推荐阅读