Importing JSON files as const?
#31969
-
|
Is it possible to import JSON files, so that I don't loose the literal information? What I want to archiveIf I have this TS array in a file:
export default [
"foo",
"bar",
"baz"
] as const; // <-- This is the important partAnd then:
import myArray from 'my_array.ts'
type MyArrayUnion = typeof myArray[number] // <-- this type is ('foo' | 'bar' | 'baz') like I wantHow the JSON import worksIf I have this JSON array in a file:
[
"foo",
"bar",
"baz"
]And I want to import it like this:
import myArray from 'my_array.json' with {type: 'json'}
type MyArrayUnion = typeof myArray[number] // <-- this type is just "string"The behavior of the JSON import works correctly as expected, but I want to know if, is it possible to archive the same as with the TS array and Why I want to do this in the first place?I want to create a function that takes the JSON file as argument and based on that argument, suggests IntelliSense for the return function. Something like this:
[
"foo",
"bar",
"baz"
]
import schema from './example.json' with { type: "json" }
export function client<Schema extends string[]>(schema : Schema) {
return {
call: (method : Schema[number]) => {
// do something with "method"
}
}
}
client(schema).call('') // <-- IntelliSense/Autocompletion for the JSON array
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
No, it's not possible, it would have to be supported in TypeScript compiler first. I suggest to open a feature request at https://github.com/microsoft/TypeScript |
Beta Was this translation helpful? Give feedback.
No, it's not possible, it would have to be supported in TypeScript compiler first. I suggest to open a feature request at https://github.com/microsoft/TypeScript