i18n-node icon indicating copy to clipboard operation
i18n-node copied to clipboard

typescript does not allow to compile code with register: global

Open CypElf opened this issue 5 years ago • 1 comments

Consider this node js exemple :

import * as yaml from 'js-yaml'
import * as i18n from 'i18n'
import * as fs from 'fs'

const en = yaml.safeLoad(fs.readFileSync("./languages/en.yml", "utf-8"))
const fr = yaml.safeLoad(fs.readFileSync("./languages/fr.yml", "utf-8"))

i18n.configure({
    locales: ['en', 'fr'],
    staticCatalog: {
        en: en as i18n.LocaleCatalog,
        fr: fr as i18n.LocaleCatalog,
    },
    register: global
})

console.log(__("some_existing_key"))

Typescript does not allow this code to compile and fail with the error message

Cannot find name '__'.

Even though the register: global part will make the function available globally. A solution is to add // @ts-ignore on the line above, and it compile successfully + the JS code generated work as intended. But it's pretty annoying to have to add it above every single usage of this as it may prevent others errors detection and would be added a very big amount of times in a big project, so I was wondering if there was another way to solve the issue. I tried to directly import at the top the functions needed to avoid having to use the register: global, but it leads to 2 problems :

  • functions need to be imported into every single code file (I have a big project in JS I want to translate to TS and as it worked without having to do that, I wish I could avoid it)
  • and the major issue is, I have no idea why, but when importing the __() function from the i18n module and using it, the functions never ever return any other language than English, even though the current locale is set to something else (this is not an issue related to the one I'm describing right now and it happens also in the standard JS library, I don't know why, it may need another issue)

So, is there another way to make typescript accept the usage of these globally registered functions ?

CypElf avatar Dec 29 '20 19:12 CypElf

well.... file a PR for https://www.npmjs.com/package/@types/i18n (out of scope of my package)

mashpie avatar Dec 29 '20 19:12 mashpie