插件窝 干货文章 TypeScript如何限制字符串变量必须以特定后缀结尾?

TypeScript如何限制字符串变量必须以特定后缀结尾?

fileName 赋值 字符串 string 47    来源:    2025-03-23

在 TypeScript 中,你可以使用模板字面量类型(Template Literal Types)来限制字符串变量必须以特定后缀结尾。模板字面量类型允许你创建基于字符串的模式匹配类型。

假设你想限制一个字符串变量必须以 .ts 结尾,你可以这样做:

type EndsWithTS = `${string}.ts`;

let fileName: EndsWithTS;

// 合法的赋值
fileName = "main.ts";
fileName = "utils.ts";

// 非法的赋值
fileName = "main.js"; // Error: Type '"main.js"' is not assignable to type '`${string}.ts`'.

解释:

  • ${string} 表示任意字符串。
  • .ts 是你希望字符串必须以 .ts 结尾的部分。

更复杂的例子:

如果你希望字符串以 .ts.js 结尾,你可以使用联合类型:

type EndsWithTSorJS = `${string}.ts` | `${string}.js`;

let fileName: EndsWithTSorJS;

// 合法的赋值
fileName = "main.ts";
fileName = "utils.js";

// 非法的赋值
fileName = "main.py"; // Error: Type '"main.py"' is not assignable to type '`${string}.ts` | `${string}.js`'.

动态后缀:

如果你希望后缀是动态的,你可以使用泛型:

type EndsWith<Suffix extends string> = `${string}${Suffix}`;

let fileName: EndsWith<".ts">;

// 合法的赋值
fileName = "main.ts";

// 非法的赋值
fileName = "main.js"; // Error: Type '"main.js"' is not assignable to type '`${string}.ts`'.

总结:

通过使用模板字面量类型,你可以轻松地限制字符串变量必须以特定后缀结尾。这种方法在 TypeScript 中非常灵活,并且可以与其他类型系统特性结合使用。