#Generating a Type from a Record<string, string[]>

8 messages · Page 1 of 1 (latest)

sullen beacon
#

What I would like is to generate a type form a Record:

const langs = {
  en: ['GB','US'],
  it: ['IT'],
};

to generate a type equivalent to:

type LanguageCode = "en-GB" | "en-US" | "it-IT";
sullen beacon
#

Appling your type I get this

type MyType<t> = {
  [k in keyof t]: t[k] extends readonly any[] ? t[k][number] : t[k];
}[keyof t];
type Result = MyType<typeof langs>;
//   ^? type Result = "GB" | "US" | "IT"
sullen beacon
#

Ok, so I was able to find a solution, could probably be simpler

const langs = {
  en: ['GB','US'],
  it: ['IT'],
} as const;

type Codes<
  T extends typeof langs = typeof langs,
  L extends keyof T = keyof T,
> = L extends string
  ? T[L] extends Readonly<Array<infer U extends string>>
    ? `${L}-${U}`
    : never
  : never;
#

!resolved

#

If anyone has some thoughts on ways to improve, feel free to leave an opinion

odd hornet
#

all you needed to do in the original type was add the key

tawdry meteorBOT
#
const langs = {
  en: ['GB','US'],
  it: ['IT'],
} as const;

type MyType<t> = {
  [k in keyof t]: t[k] extends readonly string[] ? `${k & string}-${t[k][number]}` : t[k];
}[keyof t];

type Result = MyType<typeof langs>;
//   ^? - type Result = "en-GB" | "en-US" | "it-IT"
sullen beacon