1

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?

  • IIRC, TypeScript always accepts any `string` value as a valid key type, even if `Keys` in `Record` is a subtype of `string` - that's just due to JavaScript's rules about object keys. I only ever really see the unions of string values used for `Keys` types - I struggle to think of a legitimate application of using a template-literal to restrict object keys... – Dai Jun 10 '21 at 03:41
  • Also, this sounds similar to this thread: https://stackoverflow.com/questions/13315131/enforcing-the-type-of-the-indexed-members-of-a-typescript-object – Dai Jun 10 '21 at 03:44

0 Answers0