假设我正在编写处理 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
有什么方法可以创建具有这些属性的 Flow 类型吗?我在研究中发现了 $Subtype
,并认为这可能有效:
type uuid = $Subtype<string>;
但出于某种原因,它仍然允许从字符串赋值。
最佳答案
有以下 hack(缺点是 UUID
也将是 Object
):
// keep this constructor private
class IsUUID {}
export type UUID = string & IsUUID;
export function create(): UUID {
const uuid = 'blah' // <= your implementation
return ((uuid: any): UUID)
}
// tests
declare function f(uuid: UUID): void;
declare function g(s: string): void;
declare function h(o: Object): void;
let foo = create()
let bar: string = foo // <= ok
f(foo) // <= ok
f(bar) // <= error: string. This type is incompatible with IsUUID
g(foo) // <= ok
g(bar) // <= ok
h(foo) // <= ok :(
关于javascript - Flow 中的子类型化内置类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40558780/