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

如何在TypeScript中定义不以指定字符结尾的类型?

TypeScript中如何定义不以换行符结尾的字符串类型?

在TypeScript里,我们可以用模板字面量类型轻松定义以换行符结尾的字符串:

type Paragraph = `${string}\n`;

const paragraph: Paragraph = 'foo\n'; // 符合类型要求
const word: Paragraph = 'foo'; // 不符合类型要求(报错)

那能不能定义相反的类型——不以换行符结尾的字符串类型呢?比如要实现这样的效果:

type NotParagraph = /* 这里填类型定义 */;

const paragraph: NotParagraph = 'foo\n'; // 不符合要求(报错)
const word: NotParagraph = 'foo'; // 符合类型要求

解决方案:用条件类型+模板字面量模式匹配

可以通过TypeScript的条件类型结合模板字面量的模式匹配能力,精准排除以换行符结尾的字符串:

方式1:泛型严格检查

这种方式适合对具体字符串字面量做类型校验:

type NotParagraph<T extends string> = T extends `${infer _}\n` ? never : T;

// 使用示例
const validWord: NotParagraph<'foo'> = 'foo'; // 正常通过
const invalidPara: NotParagraph<'foo\n'> = 'foo\n'; // 类型不匹配,报错

方式2:直接约束任意字符串

如果要直接定义一个能约束所有不以\n结尾的字符串的类型,可以这么写:

type NotParagraph = string extends infer T extends string
  ? T extends `${string}\n` ? never : T
  : never;

// 使用示例
const validText: NotParagraph = 'hello world'; // 正常
const invalidText: NotParagraph = 'hello world\n'; // 报错

原理说明

这里核心是利用了TypeScript对模板字面量的模式匹配能力:T extends ${string}\n``会检查字符串T是否以\n结尾,如果是就返回never(表示该类型不合法),否则返回原类型T,以此实现"不以换行符结尾"的类型约束。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 14:20:32