有什么方法可以使用流来限制特定的字符串模式? [英] Is there any way to use flow to restrict specific string patterns?

查看:57
本文介绍了有什么方法可以使用流来限制特定的字符串模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在React Web应用程序上使用Flow,目前正面临一个用例,要求用户以"HH:mm"格式输入某些时间值.有什么方法可以描述字符串遵循的是什么模式?

I'm using Flow on a React webapp and I'm currently facing a use-case where I'm asking for the user to input certain time values in a "HH:mm" format. Is there any way to describe what pattern is being followed by the strings?

我一直在寻找解决方案,但是我在某种程度上同意的一般共识似乎是您不需要使用Flow处理此类事情,而赞成使用验证函数并依赖于UI代码以遵循正确的模式提供代码.仍然,我想知道是否有什么方法可以使代码尽可能地具有描述性.

I've been looking around for a solution but the general consensus which I agree to to a certain point seems to be that you don't need to handle this kind of thing using Flow, favouring using validating functions and relying on the UI code to supply the code following the correct pattern. Still, I was wondering if there is any way to achieve this in order to make the code as descriptive as possible.

推荐答案

您要创建验证器功能,但使用了不透明类型别名进行了增强: https://flow.org/en/docs/types/opaque-types/

You want to create a validator function, but enhanced using Opaque Type Aliases: https://flow.org/en/docs/types/opaque-types/

或更具体地说,带有子类型约束的不透明类型别名:

Or, more specifically, Opaque Type Aliases with Subtyping Constraints: https://flow.org/en/docs/types/opaque-types/#toc-subtyping-constraints

您应该在定义不透明类型的同一文件中编写一个验证器函数.它将接受原始类型作为参数,并返回键入为具有子类型约束的不透明类型的值.

You should write a validator function in the same file where you define the opaque type. It will accept the primitive type as an argument and return a value typed as the opaque type with subtyping constraint.

现在,在另一个文件中,您可以键入一些变量作为不透明类型,例如在函数参数中.Flow会强制您仅传递通过验证器函数的值,但这些值可以像原始类型一样使用.

Now, in a different file, you can type some variables as the opaque type, for example in function arguments. Flow will enforce that you only pass values that go through your validator function, but these could be used just as if they were the primitive type.

示例:

exports.js :

export opaque type ID: string = string;


function validateID(x: string): ID | void {
    if ( /* some validity check passes */ ) {
        return x;
    }

    return undefined;
}

import.js :

import type {ID} from './exports';

function formatID(x: ID): string {
    return "ID: " + x; // Ok! IDs are strings.
}

function toID(x: string): ID {
    return x; // Error: strings are not IDs.
}

这篇关于有什么方法可以使用流来限制特定的字符串模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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