0
votes

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:

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
}
1
Isn't Record<"key", true> what you want ?Titian Cernicova-Dragomir

1 Answers

0
votes

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>