0

I realize it is probably against TypeScript philosophy, but thought I'd still ask.

Is it possible to convert a type literal into a string literal at compile time?

E.g., can I assign "AnotherString" to str2 below without repeating it?

// object to type, no problem
const obj = "SomeString";
let str1: typeof obj = obj;

// type into obj: ?
type SomeType = "AnotherString";
const str2: SomeType = valueof SomeType; // no such thing as valueof

1 Answer 1

3

Is it possible to convert a type literal into a string literal at compile time?

No, because types do not exist in emitted code. The JavaScript it gets compiled to is the TypeScript without all the types. (Nearly) everything that TypeScript offers is to help you while you're writing scripts, and has no effect at runtime, because it'll all get trimmed out when compiled.

This works

const obj = "SomeString";
let str1: typeof obj = obj;

because, when compiled, it's

const obj = "SomeString";
let str1 = obj;

But

type SomeType = "AnotherString";
const str2: SomeType = <something referencing SomeType>

can't work because, when compiled, the types go away, so

const str2 = <something referencing SomeType>

doesn't make sense - you can't get "AnotherString" if it doesn't exist anywhere in the JavaScript code anymore.

1
  • Thanks for confirming it. I thought, there might be a trick to "stringify" a type literal at compile time, before it gets erased. A bit like how TypeScript has enums, which become a syntax sugar for Function object.
    – noseratio
    Commented Jul 5, 2022 at 3:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.