#Can I put type into the dir variable, which is the keys in the json file?
20 messages · Page 1 of 1 (latest)
Even if you set the file like this?
const data = await import(`../../../languages/en/ping.json`);
if you know what the file path is ahead of time then yes but not with variables
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 ...
yes thanks ❤️🩹
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
suggestions?
🙂🙂🙂
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
Is there a way to scan the file when I put the name and return the keys during the time I write the code?
I hope so
if it's a static import, then yes, otherwise no
ok thx you ❤️🩹,
thx @gloomy estuary ❤️🩹