gpt4 book ai didi

typescript 模板文字类型强制结构

转载 作者:行者123 更新时间:2023-12-05 02:29:26 26 4
gpt4 key购买 nike

我有以下代码:

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

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

这按预期工作,但不会强制结构。以下内容也是有效的:

  const v: Foo = 'bar--foo'

如何强制使用 T

最佳答案

这里的问题是检查空字符串。在此处阅读有关此问题的更多信息: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

Playground link

关于 typescript 模板文字类型强制结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72197509/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com