This PR addresses 2 problems with Typescript types:
1215: By removing the type Path from the key: Key | ResourceKeys | Path, we get type inference to work again and suggest valid translations when using globally injected $t. Since the type Key extends string already extends from string, it shouldn't cause any regression. For the type inference to work when using $t, you have to extend the module types:
import en from '@src/assets/locales/en.json';
type Messages = typeof en;
declare module 'vue-i18n' {
export interface DefineLocaleMessage extends Messages {}
}
When fixing the first issue, I found that nested keys are treated as translations by themselves. For example:
{
"this": {
"is": {
"a": {
"nested": {
"key": "This is a nested key"
}
}
}
}
}
When having this en.json locale file, type inference will suggest a combination of all keys:
But this is not correct, only this.is.a.nested.key should be suggested. I've created two new types to solve this:
JsonPaths: Will return leaf keys only, and not suggest in-between keys from a JSON or Javascript object. I've called it Json because this should be used when extracting translations from JSON files.
TranslationsPaths: This will simply remove the first level of a JSON or JS object and return the JsonPaths from the second level onwards. This is used for translations coming directly from the composer, where the top-level key is the language.
I've tried not to modify existing types to avoid breaking something, and I just created these 2 new types. Here're two images of the new behavior both in $t and when using the composer:
This PR addresses 2 problems with Typescript types:
1215: By removing the type
Path
from thekey: Key | ResourceKeys | Path
, we get type inference to work again and suggest valid translations when using globally injected$t
. Since the typeKey extends string
already extends fromstring
, it shouldn't cause any regression. For the type inference to work when using$t
, you have to extend the module types:When having this
en.json
locale file, type inference will suggest a combination of all keys: But this is not correct, onlythis.is.a.nested.key
should be suggested. I've created two new types to solve this:JsonPaths
: Will return leaf keys only, and not suggest in-between keys from a JSON or Javascript object. I've called it Json because this should be used when extracting translations from JSON files.TranslationsPaths
: This will simply remove the first level of a JSON or JS object and return theJsonPaths
from the second level onwards. This is used for translations coming directly from the composer, where the top-level key is the language.I've tried not to modify existing types to avoid breaking something, and I just created these 2 new types. Here're two images of the new behavior both in
$t
and when using the composer: