1

I have different json translation files and I would like to have static typing using TypeScripts 4.1 Template Literal Types. There is a similar question but I would like to add scopes to that. The code I have is as follows:

type dict = typeof import('./login/en.json') | typeof import('./register/en.json')

type Scopes = 'login' | 'register'

type GetDictValue<T extends string, O> = T extends `${Scopes}_${infer A}.${infer B}`
  ? A extends keyof O
    ? GetDictValue<B, O[A]>
    : never
  : T extends keyof O
  ? O[T]
  : never

type CheckDictString<T extends string, O> = T extends `${Scopes}_${infer A}.${infer B}`
  ? A extends keyof O
    ? `${Scopes}_${A}.${Extract<CheckDictString<B, O[A]>, string>}`
    : never
  : T extends keyof O
  ? T
  : never

declare function t<P extends string>(p: P & CheckDictString<P, dict>): GetDictValue<P, dict>

Where login/en.json has the following contents:

{
  "foo": "Foo"
}

And register/en.json the following:

{
  "bar": "Bar"
}

However this does not work. This would be the expected result:

t('login_foo') // OK
t('login_bar') // KO
t('register_bar') // OK
t('register_foo') // KO
t('foo') // KO
t('bar') // KO

How could I achieve this? Is it possible?

César Alberca
  • 2,321
  • 2
  • 20
  • 32
  • If you have union type which has not common keys - dict, `keyof` operator will always return never instead of `'foo'|'bar'` – captain-yossarian from Ukraine Jan 15 '21 at 11:42
  • Could you please provide more context, what you want to achieve? – captain-yossarian from Ukraine Jan 15 '21 at 11:49
  • @captain-yossarian how could I workaround that? Basically I would like to add sound static typing to the Transloco library following inline loaders, so I can split my translation files per domain: https://ngneat.github.io/transloco/docs/inline-loaders – César Alberca Jan 15 '21 at 12:18
  • I will do my best, if you provide more context. What type do you expect exactly from GetDictValue with examples. SAme for CheckDictString – captain-yossarian from Ukraine Jan 15 '21 at 12:20
  • My code is based on this answer: https://stackoverflow.com/questions/58277973/how-to-type-check-i18n-dictionaries-with-typescript/58308279#58308279. The thing about that code is that it works for nested properties. If you check the other question I will probably shed more light and context – César Alberca Jan 15 '21 at 12:27

0 Answers0