[英]Can I test a string with regex using io-ts in Typescript
const a = "test-string";
const regex = new RegExp(/^t*/);
regex.test(a);
io-ts
中是否有regex.test(a)
對應項,它將在運行時檢查錯誤?
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");
正則表達式類型(還不是? ) Typescript 的一部分,因此io-ts
可能無法為您提供幫助。
但是,您可以使用Typescript 4.1 中的模板字符串來獲得類似的東西。
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
如果你想匹配字符串的子集,你需要逐步完成它:
type T = "papaya";
const a = "mango papaya pineapple";
type Test = typeof a extends `${infer head}${T}${infer tail}` ? true : false;
// type Test = true;
這是一個非常簡化的例子——它是一個非常強大的特性。 上面的鏈接有更多示例,原始 PR也是如此
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.