Prevent template literal types being converted to type `string` when used with utility type `Record`

174 Views Asked by At

I am playing with Typescript 4's template literal types. Specifically wanting to assert strings have a particular format:

type Dunder = `__${string}__`;

const test:  Dunder = '__TEST__'; // So far so good 

At this point I want to assert that an object only accepts type Dunder as keys.

const example: Record<Dunder, unknown> = {
  __fieldA__: '' //  Good
  fieldB: '' // Not good, but accepted by the compiler
};

It seems to me that it is converting Dunder to type string. This is not how I would expect the compiler to behave. Is there any work arounds to enforce this behaviour of having only keys as type Dunder?

0

There are 0 best solutions below