NuxtN
Nuxt2y ago
Gerbuuun

Typescript nested generic resolves to unknown

Am I missing something?
In the following example, shouldn't the type of result resolve to { test: { title: 'test' } }?
Instead it says it's of type Record<string, unknown>
function test<T, K extends { nested: Record<string, T> }>(data: K) {
  return data.nested;
}

const testdata = {
  nested: {
    test: {
      title: 'Test',
    }
  }
}

const result = test(testdata);

Did I reach the limits of Typescript?
Solution
In the end I actually went with this:
export default function useTranslation() {
  const { locale } = useI18n();

  type Translatable<K, T> = K & { translations: Record<string, T> };
  function translate<T, K>(data: Translatable<T, K>) {
    const { translations, ...rest } = data;
    const definedLocales = computed(() => Object.keys(translations));
    const translation = computed(() => definedLocales.value.includes(locale.value) ? translations[locale.value] : translations[definedLocales.value[0]]);
    const result = computed(() => ({ ...rest, ...translation.value }));

    return toReactive(result);
  }

  return {
    translate,
  };
}

It is a translate composable which uses the current locale given by Nuxt i18n.
I tried function translate<T>(data: { translations: Record<string, T> }) but that resolved to object instead.

See final options on typescript play
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
Was this page helpful?