在打字稿中声明字符串的最小/最大长度 [英] Declaring string type with min/max length in typescript

查看:77
本文介绍了在打字稿中声明字符串的最小/最大长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

After going through the docs, it seems there is no direct way to type check for min/max length of a string datatype.

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

But, is there a way to declare a string datatype using some custom types so that it checks whether the string length is with the given bounds?

推荐答案

使用类型构造函数和称为幻影类型的东西(阅读有关),这是一种确保不能将类型直接分配给值的技术。

You can achieve this using a type constructor and something called a "Phantom Type" (read a nice article about this here) which is a technique to ensure that a type can not be assigned to a value directly.

以下是 StringOfLength< Min,Max> 类型:

type StringOfLength<Min, Max> = string & {
  __value__: never // 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 { __value__: never }

这里有一些限制-无法阻止某人创建无效类型,例如 StringOfLength< -1,-300> ,但是您可以添加运行时检查传递给 stringOfLength 构造函数的 min max 值有效。

There are some limitations here - which are that you can't prevent someone from creating an invalid type like StringOfLength<-1, -300> but you can add runtime checks that the min and max values passed to the stringOfLength constructor function are valid.

这篇关于在打字稿中声明字符串的最小/最大长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆