Declaring string type with min/max length in typescript

拟墨画扇 提交于 2019-12-13 15:24:57

问题


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?


回答1:


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.

Here's an example of a StringOfLength<Min,Max> type using these techniques:

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 }

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.




回答2:


Javascript is weakly typed. You are probably expecting a statically typed language behaviour like C.

You don't do that in Javascript. Instead you programatically check the type and length (validate) your variables/input.



来源:https://stackoverflow.com/questions/51813272/declaring-string-type-with-min-max-length-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!