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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With