【问题标题】:Is it possible with flow-type to typecheck for simple types such as a uri是否可以使用流类型对简单类型(例如 uri)进行类型检查
【发布时间】:2018-07-15 23:45:13
【问题描述】:

说,我有一个函数,它接受一个字符串,并确保它是一个有效的 uri:

function checkUri(input: string): Uri {

}

是否可以将这种新类型 Uri 定义为只能由该 checkUri 方法发出,即使我真的只是希望它是一个字符串?

我的最终目标是我想定义一堆具有Uri 属性的类型,并且我想通过我的类型系统强制执行验证。

所以从外部看,Uri 类型看起来和行为就像一个保证已经过验证的不可变字符串。

【问题讨论】:

标签: javascript node.js flowtype


【解决方案1】:

要扩展我的评论(其中拼写错误opaque),here's an try flow example

// declaring in the try makes it act as if it were imported, but I'll just import here
import { checkUri, type Uri } from 'some-file';

function useUri(uri: Uri): void {}

// $ExpectError
useUri('some string')

// this one works
useUri(checkUri('some string'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 2011-09-26
    相关资源
    最近更新 更多