/ TypeScript Public
[Feature] Import non-js content as const string #42219
Awaiting More Feedback
This means we'd like to hear from more people who would be helped by this feature
An idea for TypeScript
There is a need for a way to import non-js content and process that content to produce TypeScript definitions, as asked for in for example #16607. But with the template literal types introduces in TS 4.1 I believe most of this can be solved without a plugin system. There are examples of projects that parse strings representing for example SQL, and produces useful types based on the string value. So given only the string content of a file it is possible to declare a module with useful types.
import module string
My suggestion meets these guidelines:
My proposal is something like this:
import.meta.contenthere as an example of how it could work. import.meta will contain many possible properties, so I'm just using
contenthere as an idea)
This way the actual textual value of the file could be known both in the editor and at compile time. For example:
This isn't very useful in and of itself, but with template literal types it is now possible to parse and make use of other languages.
For example, when using css modules it is useful when the IDE can help and show all the classes in the css file. Here is a trivally simple (and therefore not completely working) example of how this can be done:
(The code above can be tested here
Given a simple css file with classes this declaration will make it possible to import the file and use the classes in a project, like this:
This is just a simple example, there are many examples of parsing and working with strings that represent json and sql here. Something I've been looking into is parsing glsl files and extracting the list of uniforms and their types. I'm sure there are many other usecases for parsing the string into a type declaration.
So to summarize, by making the string content of a file available in a module declaration, existing features of TypeScript, like template literal types, makes it possible to parse the string and producing useful types.
The text was updated successfully, but these errors were encountered: