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?