想象一下我有这样的流类型。
type Sample = {
someProp: "foo" | "bar";
arr: Array<string | number>
}
这个想法是我想根据用于someProp
的字符串值来强制使用数组的类型。换句话说,如果说someProp
的类型是“ foo”,我希望arr
的类型是Array<string>
,但是如果someProp
的类型是“ bar” ,我希望arr
的类型为Array<number>
。
我知道我的示例方法可能不可行,所以我想我想问我将如何做到这一点。我当时正在考虑以某种方式使用泛型,但我根本不了解如何解决这个问题。
答案 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"]
}