Home > Blockchain >  How can I build a Typescript string literal type with an imported array?
How can I build a Typescript string literal type with an imported array?

Time:10-25

In one of my config files config.js file, I have:

module.exports = {
    locales: ['en', 'fr']
}

In my library, I try to import the config.js file and turn it into a typescript liberal type like so:

import config from "config.js"

const tempDefaultLocales = [...config.locales] as const
export type Language = typeof tempDefaultLocales[number]

But the type of Language is string and not "en" | "fr"

If I don't import and just hard type it, the as const works. Example:

const locales = ["en","fr"] as const
type Language = typeof locales[number]

Gives me the correct type of "en" | "fr"

Any idea how I can make this work without changing my config file to ts or hardcoding it?

Here is a sandbox: enter image description here

CodePudding user response:

Define the exported object as a const. Working example here.

module.exports = {
    locales: ['en', 'fr']
} as const

as const does not "propogate". You cant define another variable somewhere else that isn't a const and then assume it will treat it as one because the as const guarantees are missing on the source data, so typescript can't guarantee it won't change or be added to by some other code.

  • Related