You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何反转模板字面量类型?定义首字符不为/的字符串类型

如何定义首字符不为/的字符串类型?

首先,我们已经有了强制要求以/开头的字符串类型:

type StartsWithSlash = `/${string}`;

要反转这个约束,定义一个接受**首字符不为/**的任意字符串类型,有两种实用的实现方式:

方式一:泛型条件类型过滤

这种方式通过条件类型直接排除以/开头的字符串:

type DoesNotStartWithSlash<T extends string = string> = T extends `/${infer _}` ? never : T;

逻辑很直接:如果传入的字符串T是以/开头的,就返回never(表示该类型不被允许),否则保留原类型T。不指定泛型参数时,它会自动匹配所有符合要求的字符串。

方式二:模板字面量直接构造

我们也可以直接构造出符合规则的字符串结构:

type DoesNotStartWithSlash = '' | `${Exclude<string, '/'>}${string}`;

拆分来看:

  • '' 空字符串本身没有首字符,符合要求;
  • ${Exclude<string, '/'>} 确保首字符不是/;
  • 后面跟上${string}允许首字符之后是任意内容。

验证示例

// 合法的赋值
const validEmpty: DoesNotStartWithSlash = '';
const validNormal: DoesNotStartWithSlash = 'home/page';
const validSingleChar: DoesNotStartWithSlash = 'a';

// 会触发类型错误的赋值
const invalidSlashStart: DoesNotStartWithSlash = '/dashboard'; // ❌
const invalidSingleSlash: DoesNotStartWithSlash = '/'; // ❌

内容的提问来源于stack exchange,提问作者cyborgx99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 22:12:23