GregRos GregRos - 25 days ago 22
TypeScript Question

Turn a string literal type to a literal value

In TypeScript, we can have string literal types that allow us to do things like:

type HelloString = "Hello";


This lets me define something like a string enum as follows:

namespace Literals {
export type One = "one";
export type Two = "two";
}


And then I can define a union:

type Literal = Literals.One | Literals.Two;


Is there a way to extract the unique value of
Literals.One
as the type
Literals.One
?

The reason for this, is that when I define a function like this:

function doSomething(literal : Literal) {

}


I'd really love to do the following:

doSomething(Literals.One);


But I can't. I have to write:

doSomething("one");

Answer

You can have types and values with the same name inside a namespace, so you can define constants for those values:

namespace Literals {
    export type One = "one";
    export type Two = "two";
    export const One: One = "one";
    export const Two: Two = "two";
}

const s: Literals.One = Literals.One;
console.log(s);

There is a probosal on github for string enums, they suggest the current best solution is the example above.

Comments