Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Template Literal Type

Has anyone ever ran Typescript template literal not being able to recognize the type if it's constructed using a variable before?

Here's the code snippet:

const namespace = 'myNamespace';

type Keys = 'a' | 'b';

type NamespacedKeys = `${typeof namespace}/${Keys}`;

type NamespacedObjects = Record<NamespacedKeys, string>;

const foo: NamespacedObjects = {
  [`${namespace}/a`]: 'bar',
  [`${namespace}/b`]: 'toto',
} // this would have an error -> Type '{ [x: string]: string; }' is missing the following properties

const baz: NamespacedObjects = {
  'myNamespace/a': 'bar',
  'myNamespace/b': 'yolo',
} // this works 

like image 338
bbbryan14 Avatar asked Apr 01 '26 04:04

bbbryan14


1 Answers

The problem is that the compiler does not automatically infer a template literal type when it encounters a template literal expression. For example:

const key = `${namespace}/a`; 
// const key: string

The inferred type of key is just string and not a string literal. If you want the compiler to infer a string literal type for that, you need to explicitly ask it to do so with a const assertion:

const key2 = `${namespace}/a` as const; 
// const key2: "myNamespace/a"

Wondering why this doesn't happen automatically? Well, there was work done in microsoft/TypeScript#41891 to do this... and it apparently broke a bunch of real world code that was already using template literal expressions but depending on its type being just string and not some string literal. So this was reverted in microsoft/TypeScript#42588. For now we will just have to use a const assertion, at least until the TS team figures out how to get better behavior without breaking too much existing code:

const foo: NamespacedObjects = {
  [`${namespace}/a` as const]: 'bar',
  [`${namespace}/b` as const]: 'toto',
} // okay

Playground link to code

like image 63
jcalz Avatar answered Apr 02 '26 18:04

jcalz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!