Home > front end >  Turning type literal into string literal in TypeScript
Turning type literal into string literal in TypeScript

Time:07-06

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

CodePudding user response:

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.

  • Related