简体   繁体   中英

Can I test a string with regex using io-ts in Typescript

const a = "test-string";
const regex = new RegExp(/^t*/);

regex.test(a);

Is there a regex.test(a) counterpart in io-ts which will check for error during runtime?

import * as t from "io-ts";

export interface MyRegexBrand {
  readonly MyRegex: unique symbol;
}

export type MyRegex = t.Branded<string, MyRegexBrand>;

export interface MyRegexC extends t.Type<MyRegex, string, unknown> {}

const re = /ab+c/;

export const MyRegex: MyRegexC = t.brand(
  t.string,
  (s): s is MyRegex => re.test(s),
  "MyRegex",
);

const result = MyRegex.decode("something");

Regex types are not ( yet? ) part of Typescript, so io-ts won't likely be able to help you.

You can however use template strings from Typescript 4.1 to get something similar.

type T = "test-string";

const a = "test-string";
type Test1 = typeof a extends T ? true : false;
// type Test1 = true

const b = "something-different";
type Test2 = typeof b extends T ? true : false;
// type Test2 = false

If you want to match on subsets of the string you'll need to do step through it in pieces:

type T = "papaya";
const a = "mango papaya pineapple";
type Test = typeof a extends `${infer head}${T}${infer tail}` ? true : false;
// type Test = true;

This is a very simplified example - it's a very powerful feature. The link above has more examples, as does the original PR

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM