Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript template literals type force structure

Tags:

typescript

I have the following code:

type Foo<T extends string = string> = `bar-${T}-foo`;

const v: Foo = 'bar-g-foo'

That works as expected, but it doesn't force the structure. The following is also valid:

  const v: Foo = 'bar--foo'

How can I force the usage of T?

like image 629
undefined Avatar asked Dec 29 '25 06:12

undefined


1 Answers

The problem here is to check for an empty string. Read more about this problem here: How to write a string type that does not contain an empty string in TypeScript

Based on the stack from above you could do something like this:

type Character = 'a' | 'b' | 'c' | ... ; // Here all possible 1 letter strings
type NonEmptyString = `${Character}${string}`;
type Foo<T extends string = NonEmptyString> = `bar-${T}-foo`;

const v: Foo = 'bar-a-foo' // ✔
const x: Foo = 'bar--foo' // ❌ Type '"bar--foo"' is not assignable to type

Playground link

like image 106
Lars Flieger Avatar answered Jan 01 '26 20:01

Lars Flieger