#How to make union from object props?

24 messages ยท Page 1 of 1 (latest)

grim tuskBOT
#
OnkelTem#4669

Preview:```ts
type A = {
foo: "a",
bar: "b"
}

// Need to make a type
type ATarget = {
key: "foo"
} | {
key: "bar"
}

type GetATarget = A extends {[infer K]: any} ? K : 0```

near coyote
#

I know there is a parsing error, however I'm not sure about the correct syntax

#

And the right part should be something like:

#
type GetATarget = A extends { [infer K]: any } ? { key: K } : 0
grim tuskBOT
unique nymph
#

!ts

grim tuskBOT
#
type A = {
  foo: "a",
  bar: "b"
}

// Need to make a type
type ATarget = {
  key: "foo"
} | {
  key: "bar"
}

type GetATarget<K extends keyof A = keyof A> = K extends K ? { key: K; } : never
type GetATarget_ = GetATarget
//   ^? - type GetATarget_ = {
//       key: "foo";
//   } | {
//       key: "bar";
//   }```
near coyote
#

Ha, so it's a trick to add a parameter

#

while you actually don't need one

unique nymph
# near coyote while you actually don't need one

yeah. you can also do keyof A extends infer K ? K extends K as another way to trigger distributive conditional types (if you want to avoid the extra generic parameter), but i think that's even more difficult to understand

near coyote
#

@unique nymph thanks! I did it:

grim tuskBOT
#
OnkelTem#4669

Preview:```ts
type VoiceDefs = {
ru: {v1: [1, 2]; v2: [3]}
en: {v3: [4, 5]}
}

type FlattVoiceDefs = keyof VoiceDefs extends infer K
? K extends K
? K extends keyof VoiceDefs
? keyof VoiceDefs[K] extends infer P
? P extends P
? P extends keyof VoiceDef
...```

near coyote
#

However it looks monstrous ๐Ÿ™‚

#

ru - lang code
v1, v2 - voices
1, 2, 3 - variants (roles)

#

This is Yandex TTS definitions, for this table:

unique nymph
#

smh don't use any

near coyote
#

Yeah, I was too quick to fix that ๐Ÿ™‚

#

put unknown instead

unique nymph
#

the nasty Values<{ mapped type }> hack should work here

grim tuskBOT
unique nymph
#

!ts

grim tuskBOT
#
type VoiceDefs = {
  ru: { v1: [1, 2]; v2: [3] };
  en: { v3: [4, 5] };
};

type Values<T> = T[keyof T];
type FlatVoiceDefs = Values<{
//   ^? - type FlatVoiceDefs = Values<{
//       v1: {
//           lang: "ru";
//           voice: "v1";
//           roles: 2 | 1;
//       };
//       v2: {
//           lang: "ru";
//           voice: "v2";
//           roles: 3;
//       };
//   }> | {
//       lang: "en";
//       voice: "v3";
//       roles: 4 | 5;
//   }
  [K in keyof VoiceDefs]: Values<{
    [P in keyof VoiceDefs[K]]: {
      lang: K;
      voice: P;
      roles: VoiceDefs[K][P] extends readonly (infer Item)[] ? Item : never;
    };
  }>;
}>;
unique nymph
#

(@near coyote)