1

With a given Record<string, SomeInterface> dictionary, I want to a union of "special" keys that can omit a specific prop from value

Here is an intuitive attempt at an implementation that unfortunately doesn't work:

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 }
}

Giving me the error:

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)

I was expecting { "foo1": { x: "some string" }} to be assignable to MixedDictionary, because is it assignable to Dictionary<FooKeys, Foo>, but somehow this isn't enough.

Is there a straight-forward way to achieve my use-case?

PLAYGROUND LINK HERE

Michal Kurz
  • 1,592
  • 13
  • 41
  • 1
    No, this is not directly possible. See the [answer to a similar question](https://stackoverflow.com/a/61434547/2887218) for the various possibilities and workarounds. If I translate that code to your question it yields [this, see in the Playground](https://tsplay.dev/w11Xkw). Good luck! – jcalz Sep 15 '21 at 15:36

0 Answers0