0

I am wondering if there is a way to create types that are verified by a function in Typescript/React.

Instead of a 'string' type for example, I would like it to be a regex expression:

interface Verify
{
  email: /.+@.*\.com/g;
}

The regex may not work but the concept is of a prop type being a string matching the regex.

A more generalized and useful is to have the input pass through a function to verify it:

interface AcceptableInput
{
  input: checkIfInputIsAcceptable(input)
}
let obj: AcceptableInput = { input: "works@working.com" }

Then to check if the input is of the correct type it would check with a function:

function checkIfInputIsAcceptable(input)
{
  if(typeof input === "string)
    return true;
  if(input instanceof AnotherInterface)
    return true;
  return false;
}

The code does not work, but I hope it exemplifies the concept I am asking about. I am not sure if this is possible. Any workarounds would also be appreciated.

1 Answers1

0

TypeScript won't really do any complex validation because it's fairly pointless (because you can solve the same issue in different ways, see below) and it heavily complicates the type system. The best way to do something like this is probably via type guards and runtime validation code. (see https://www.typescriptlang.org/docs/handbook/advanced-types.html)

If you're matching against a very basic string pattern then you could also consider looking into template literal types which were added in Typescript 4.1 (see https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html)

Mats Jun
  • 351
  • 2
  • 8