首页 > 解决方案 > 在打字稿中声明具有最小/最大长度的字符串类型

问题描述

浏览完文档后,似乎没有直接的方法来检查字符串数据类型的最小/最大长度。

但是,有没有办法使用一些自定义类型来声明字符串数据类型,以便检查字符串长度是否在给定的范围内?

标签: javascriptstringtypescriptvalidationconstraints

解决方案


您可以使用类型构造函数和称为“幻象类型”的东西来实现这一点(在此处阅读一篇不错的文章),这是一种确保不能直接将类型分配给值的技术。

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和值有效。maxstringOfLength


推荐阅读