我有以下代码:
type Foo<T extends string = string> = `bar-${T}-foo`;
const v: Foo = 'bar-g-foo'
这就像预期的那样,但它不会迫使 struct .以下内容同样有效:
const v: Foo = 'bar--foo'
我怎样才能强制使用T
?
我有以下代码:
type Foo<T extends string = string> = `bar-${T}-foo`;
const v: Foo = 'bar-g-foo'
这就像预期的那样,但它不会迫使 struct .以下内容同样有效:
const v: Foo = 'bar--foo'
我怎样才能强制使用T
?
这里的问题是check for an empty string.阅读更多关于这个问题的信息:How to write a string type that does not contain an empty string in TypeScript
根据上面的堆栈,您可以执行以下操作:
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