Home > Back-end >  Typescript: vue-i18n excess property check
Typescript: vue-i18n excess property check

Time:09-08

Consider 2 languages defined in JSON:

jp.json

{
    "hello": "こんにちは"
}

ge.json

{
    "hello": "hallo",
    "world": "welt"
}

Now, let's pass the languages to create an i18n object:

import { createI18n } from 'vue-i18n'
import jp from '@/i18n/jp.json'
import ge from '@/i18n/ge.json'

type Schema = typeof jp

const i18n = createI18n<[Schema], 'jp' | 'ge', false>({
    legacy: false,
    locale: 'jp',
    fallbackLocale: 'jp',
    messages: {
        jp,
        ge
    }
})

I would like jp.json to be the source of truth language schema, but the way described above does not check for excess properties contained in ge.json ("world": "welt") and does not throw an error. Is there a way to do so?

Note: the language files are quite big and I need to import them.

CodePudding user response:

Unfortunately I think the easiest option is to use a generic function to do the checking for you:

function conformsTo<T>(messages: { [K in keyof T]: Schema extends T[K] ? T[K] : never }) {
    return messages;
}

const i18n = createI18n<[Schema], 'jp' | 'ge', false>({
    legacy: false,
    locale: 'jp',
    fallbackLocale: 'jp',
    messages: conformsTo({
        jp,
        ge, // error
    }),
});

Playground

  • Related