Can a type literal be converted into a string literal at compile time?
Unfortunately, it is not possible to convert a type literal into a string literal at compile time. This is because types do not exist in the emitted code. In JavaScript, TypeScript is compiled without any types, so all the type-related information is removed during compilation. The features provided by TypeScript are mainly for assisting you while writing scripts and have no impact at runtime.
For example,
const obj = "SomeString";
let str1: typeof obj = obj;
is valid, but when compiled, it becomes:
const obj = "SomeString";
let str1 = obj;
On the other hand, trying to assign a type literal like this:
type SomeType = "AnotherString";
const str2: SomeType = <something referencing SomeType>
would not work because, during compilation, the types are stripped away. Therefore, the statement would become:
const str2 = <something referencing SomeType>
This results in an error since the specific type "AnotherString
" no longer exists in the JavaScript code after compilation.