简体   繁体   English

Typescript 模板文字类型强制结构

[英]Typescript template literals type force structure

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 ?我怎样才能强制使用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在此处阅读有关此问题的更多信息: 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 游乐场链接

It might not be the best approach, becasue of the reliance on the function assigning the value of generic type dynamically, but depending on your usage this could also be vallid这可能不是最好的方法,因为依赖 function 动态分配泛型类型的值,但根据您的使用情况,这也可能是有效的

type NonEmptyString<T extends string> = T extends "" ? never : T;

function fn<T extends string>(a: `bar-${NonEmptyString<T>}-foo`) {
    // ...
}

fn("bar--foo"); // Error
fn("bar-g-foo"); // No error
fn("bar-gg-foo"); // No error

Playground link 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM