Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

limit type variable to literal type in Typescript

Consider this code:

type T<A> = {
    [A]: true
}

Given this type, I would like to use it like this:

type Obj = T<"key">

To produce type equivalent to this type:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type Obj = {
   key: true
}

But, the compiler is giving me this error:
A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1170)

Can I somehow prove, that the A type variable can only by a string literal? Something like:

type T<A extends ?literal?> = {
    [A]: true
}

>Solution :

Something like this. A extends keyof any is not exactly literal type, so we need to use mapped types here.

type T<A extends keyof any> = {
  [K in A]: true;
};

// It's equivalent to built-in Record type, so you should probably use it
// type T<K extends keyof any> = Record<K, true>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading