Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/383.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 子类型化流中的内置类型_Javascript_Flowtype - Fatal编程技术网

Javascript 子类型化流中的内置类型

Javascript 子类型化流中的内置类型,javascript,flowtype,Javascript,Flowtype,假设我正在编写处理UUID的代码。在内部,我希望将它们表示为字符串。也就是说,每个UUID都是一个字符串,但不是每个字符串都是有效的UUID,我不想意外地将错误的内容分配给一个用于保存UUID的变量。因此,我想创建一个类型“uuid”,这样分配就会失败: let foo: uuid = "Some string" 但这应该成功: function create_uuid(): uuid; { /* implementation? */ } let foo: uuid = create_uuid

假设我正在编写处理UUID的代码。在内部,我希望将它们表示为字符串。也就是说,每个UUID都是一个字符串,但不是每个字符串都是有效的UUID,我不想意外地将错误的内容分配给一个用于保存UUID的变量。因此,我想创建一个类型“uuid”,这样分配就会失败:

let foo: uuid = "Some string"
但这应该成功:

function create_uuid(): uuid; { /* implementation? */ }
let foo: uuid = create_uuid(); 
let bar: string = uuid;  // this is fine
有没有办法创建具有这些属性的流类型?我在研究中发现了
$Subtype
,并认为这可能有效:

type uuid = $Subtype<string>;
type uuid=$Subtype;

但出于某种原因,它仍然允许从字符串赋值。

有以下缺陷(缺点是
UUID
也将是
对象
):

//保持此构造函数私有
类IsUUID{}
导出类型UUID=string&IsUUID;
导出函数create():UUID{

const uuid='blah'/编辑:此答案已过期。自提出此问题以来,流已实现不透明类型。请参阅ESRogs的答案


可能有一些黑客可以解决这个问题,但您所要求的是一个名为a的流,目前不支持它们。以下是GitHub上的流存储库中的这些黑客。

使用带有子类型约束的不透明类型。来自文档:

exports.js

export opaque type ID: string = string;
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.
}
imports.js

export opaque type ID: string = string;
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.
}

AFAIK,flow无法定义字符串的某些特定子类型。例如,它无法区分“某些字符串”和“uuid字符”。它们是字符串的等效子类型。我只想为某些情况添加另一种可能的解决方案:
导出类uuid扩展字符串{}
。字符串对象与字符串不完全相同,但在许多其他方面与字符串类似-例如,JSON.Stringify()将字符串化为字符串而不是对象。