【问题标题】:How to constrain a type based on another type with flow?如何使用流约束基于另一种类型的类型?
【发布时间】:2019-05-24 09:16:55
【问题描述】:

想象一下我有一个这样的流类型。

type Sample = {
    someProp: "foo" | "bar";
    arr: Array<string | number>
}

我的想法是我想根据用于someProp 的字符串值来强制执行数组类型。换句话说,如果说someProp 的类型是“foo”,我希望arr 的类型是Array&lt;string&gt;,但是如果someProp 的类型是“bar”,我想要@987654328 的类型@成为Array&lt;number&gt;

我知道我的示例的方法可能不正确,所以我想我是在问我将如何做到这一点。我正在考虑以某种方式使用泛型,但我根本不明白如何去做。

【问题讨论】:

  • this 有帮助吗?

标签: javascript flowtype


【解决方案1】:

使用$Call 实用程序类型(https://flow.org/en/docs/types/utilities/#toc-call),您可以相对轻松地约束它。当你想进一步泛化它时会变得更难,但如果你可以在你的类型中使用字符串文字值,那么你应该没问题

type Sample<T: "foo" | "bar"> = {
    someProp: T,
    arr: Array<Constrained<T>>
}

type Constrained<T: string> = $Call<("foo" => string) & ("bar" => number), T>

let x: Sample<"foo"> = {
  someProp: "foo",
  arr: ["hello", "no numbers", "here", 2]
}

let y: Sample<"bar"> = {
  someProp: "bar",
  arr: [1, 2, 3, "oops"]
}

Try Link

【讨论】:

    猜你喜欢
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多