javascript - 在打字稿中声明具有最小/最大长度的字符串类型
问题描述
浏览完文档后,似乎没有直接的方法来检查字符串数据类型的最小/最大长度。
但是,有没有办法使用一些自定义类型来声明字符串数据类型,以便检查字符串长度是否在给定的范围内?
解决方案
您可以使用类型构造函数和称为“幻象类型”的东西来实现这一点(在此处阅读一篇不错的文章),这是一种确保不能直接将类型分配给值的技术。
StringOfLength<Min,Max>
以下是使用这些技术的类型示例:
type StringOfLength<Min, Max> = string & {
StringOfLength: unique symbol // this is the phantom type
};
// This is a type guard function which can be used to assert that a string
// is of type StringOfLength<Min,Max>
const isStringOfLength = <Min extends number, Max extends number>(
str: string,
min: Min,
max: Max
): str is StringOfLength<Min, Max> => str.length >= min && str.length <= max;
// type constructor function
export const stringOfLength = <Min extends number, Max extends number>(
input: unknown,
min: Min,
max: Max
): StringOfLength<Min, Max> => {
if (typeof input !== "string") {
throw new Error("invalid input");
}
if (!isStringOfLength(input, min, max)) {
throw new Error("input is not between specified min and max");
}
return input; // the type of input here is now StringOfLength<Min,Max>
};
// Now we can use our type constructor function
const myString = stringOfLength('hello', 1, 10) // myString has type StringOfLength<1,10>
// the type constructor fails if the input is invalid
stringOfLength('a', 5, 10) // Error: input is not between specified min and max
// The phantom type prevents us from assigning StringOfLength manually like this:
const a: StringOfLength<0, 10> = 'hello' // Type '"hello"' is not assignable to type { StringOfLength: unique symbol }
这里有一些限制 - 您无法阻止某人创建无效类型,StringOfLength<-1, -300>
但您可以添加运行时检查以确保传递给构造函数的min
和值有效。max
stringOfLength
推荐阅读
- firebase - Firebase 安全规则——使用用户文档中的属性
- python - 如何循环和优化数据提取 - Python
- javascript - 错误:products.map 不是函数 Mern Stack
- asp.net-core - 如何在不按 CTRL 键的情况下使用 ASP.NET 在选择元素中选择多个项目?
- java - 我在这个程序中遇到了一个排序问题,帮我解决这个问题
- c++ - 为所有 clion 项目包含相同的头文件
- javascript - 对于模型 \"USER\" 的路径 \"_id\" 中的值 \"post\"(类型字符串),转换为 ObjectId 失败
- react-native - 博览会退出后不会发布apk
- swift - Swift 中自动调整大小的集合视图单元格
- html - 是否可以在 HTML 中将字母屏蔽为空格?在这种情况下,我想将 UNDERSCORE(_) 屏蔽为空格