如何使用流将另一个类型约束为一个类型?

时间:2018-12-26 00:18:32

标签: javascript flowtype

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

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

这个想法是我想根据用于someProp的字符串值来强制使用数组的类型。换句话说,如果说someProp的类型是“ foo”,我希望arr的类型是Array<string>,但是如果someProp的类型是“ bar” ,我希望arr的类型为Array<number>

我知道我的示例方法可能不可行,所以我想我想问我将如何做到这一点。我当时正在考虑以某种方式使用泛型,但我根本不了解如何解决这个问题。

1 个答案:

答案 0 :(得分: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