#Can I put type into the dir variable, which is the keys in the json file?

20 messages · Page 1 of 1 (latest)

burnt vortex
#

you can't, you'd have to manually create a type

dense fern
gloomy estuary
#

This is how I load my localisations in.

#

Maybe it will be of some help.

burnt vortex
sinful doveBOT
#
ascor8522#0

Preview:ts export default async function ( locale: string, file: string ) { const data = await import( `../../../languages/${locale}/${file}.json` ) return (dir: string) => dir .split(".") .reduce( ( accumulator: | Record<string, string> | undefined | string, currentKey: string ) => typ ...

fossil kindle
#

can be simplified quite a bit

#

note it's not 100% correct in terms of types

dense fern
#

offered suggestions:

type JSONValue = string | number | boolean | JSONObject | JSONArray;
interface JSONObject { [key: string]: JSONValue; }
interface JSONArray extends Array<JSONValue> { }

type Path<T> = T extends string | number | boolean | JSONArray
  ? never
  : { [K in keyof T]: K extends string
    ? T[K] extends JSONObject
    ? `${K}.${Path<T[K]>}`
    : K
    : never
  }[keyof T];

export default async function getTranslate(locale: string, file: string) {
  const data = await import(`../../../languages/en/interactionCreate.json`);

  return (dir: Path<typeof data>) => dir
    .split('.')
    .reduce((accumulator: Record<string, string> | undefined | string, currentKey: string) =>
      typeof accumulator === "object" && accumulator[currentKey] !== undefined ? accumulator[currentKey] : "", data as Record<string, any>);
}

async () => {
  const t = await getTranslate("en", "interactionCreate");

  t("") // offered suggestions
}

but here not work

type JSONValue = string | number | boolean | JSONObject | JSONArray;
interface JSONObject { [key: string]: JSONValue; }
interface JSONArray extends Array<JSONValue> { }

type Path<T> = T extends string | number | boolean | JSONArray
  ? never
  : { [K in keyof T]: K extends string
    ? T[K] extends JSONObject
    ? `${K}.${Path<T[K]>}`
    : K
    : never
  }[keyof T];

export default async function getTranslate(locale: string, file: string) {
  const data = await import(`../../../languages/${locale}/${file}.json`);

  return (dir: Path<typeof data>) => dir
    .split('.')
    .reduce((accumulator: Record<string, string> | undefined | string, currentKey: string) =>
      typeof accumulator === "object" && accumulator[currentKey] !== undefined ? accumulator[currentKey] : "", data as Record<string, any>);
}

async () => {
  const t = await getTranslate("en", "interactionCreate");

  t("") // not offered suggestions
}

@gloomy estuary @fossil kindle

fossil kindle
#

suggestions?

dense fern
fossil kindle
#

because the compiler doesn't know what JSON file gets imported

#

because it's dynamic

#

so it doesn't know the shape of the object

#

and can't provide the list of keys

dense fern
fossil kindle
#

if it's a static import, then yes, otherwise no

dense fern