0

i have this type TypeJsonRootKeys ready to be consumed by other files, all working.

Sample json:

// sample.json
{
  "greetings": {
    "hello": "Hello",
        "hello_informal": "Hi",
        "good_morning": "Good morning",
        "good_afternoon": "Good afternoon",
        "good_night": "Good night",
        "bye": "Bye"
  },
  "commons": {
    "pagination": {
            "first_page": "First page",
            "last_page": "Last page",
            "next_page": "Next page",
            "previous_page": "Previous page"
        }
  },
  "home": "Home sweet home"
}
// file 1
import myjson from '../public/sample.json'

export type TypeJsonRootKeys = keyof typeof myjson

By external requirements i need to split this into two files. I don't know if this is possible, figuring out how to make the type TypeJsonRootKeys get the values from another file.

// file1 Type declaration pending of type Parameters
export type TypeJsonRootKeys<AnyJson> = keyof typeof AnyJson ❓

Having a 2º file in another part of the project importing both the .json file and the type to assign that json and generate the keys.

// file2 where the json will be now accesible for import, and trying to assign to the type
import someJsonData from '../public/sample.json'
import type { TypeJsonRootKeys } from '@/file1'

// Assing here somehow
TypeJsonRootKeys<someJsonData> ❓

And have other files consuming TypeJsonRootKeys which should display

// file x
import type { TypeJsonRootKeys } from '@/file1'

// allowed values should be "greetings" | "commons" | "home"
const home:TypeJsonRootKeys = 'home' ✅
const house:TypeJsonRootKeys = 'house' ❌

i am with the doc, but cannot figure out how to achieve this. Thanks in advance!

Héctor León
  • 2,210
  • 2
  • 23
  • 36
  • 1
    did you try `export type TypeJsonRootKeys = keyof typeof json1 | keyof typeof json2`? – Sysix Sep 02 '22 at 23:44
  • 1
    No, `typeof` requires a value, not a type. You cannot abstract `typeof` this way. See the answer to [this question](https://stackoverflow.com/q/50376977/2887218) for a lengthy explanation for why `typeof` does not work this way. You will need to write `X`, but then of course `type X = keyof T` isn't worth it. It's not clear to me how you intend the multiple-file thing to work though, or why abstracting `typeof` would help you do that. You'd still need `type Both = X | X`, no matter what magic `X` does. So I'm confused what you're looking for. – jcalz Sep 03 '22 at 00:35
  • Thanks @jcalz, i am looking for a way to move out Typing as external dependency. Then import it, pass the Json and use all the rest of the dependency as expected. All is done minus this "external assignment" of the json to the `keyof typeof` Type which will be consume for both the dependency itself and me. – Héctor León Sep 03 '22 at 07:08

0 Answers0