访问嵌套流类型

时间:2018-02-13 09:30:49

标签: javascript flowtype

我有一个“大”类型(在这种情况下由继电器生成),有很多嵌套正在进行。现在我需要访问嵌套类型。

示例:我如何在这里访问“某事”?

/* @flow */

type nested = {
 anArray: $ReadOnlyArray<{something: "BLA" | "TEST"}> 
}

type nestedString = $PropertyType<
  $PropertyType<nested, 'anArray'>,
  'something'
>; 

 const text: nestedString = "TEST"

链接到Flow REPL(需要切换到0.64,因为0.65目前无效):

https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAodAXAngBwKZgB2eAzhngCZgC8YA3qmAIaECCATu01gFxgAkAJTxMKAeUIwsHLlgA8dEnAC2eDAAsAloQDmfAEQAhADKt9YAD5h9AFQCiAZRv6AvgD4wqF40-Z8RUnIKBwx2bR0aAQAFdjh8dmwbXDw5H34YuLwErCT8OWIySgAaMAByFhluUrcin1KlVQ1w0tQ3AG5PME6AYzhCMjByAA8MPgKgkLDdSNtHZyA

2 个答案:

答案 0 :(得分:3)

我将此分为几种类型,以便更容易理解:

type nested = {
 anArray: $ReadOnlyArray<{something: "BLA" | "TEST"}> 
}

type ArrayType = $PropertyType<nested, 'anArray'>;

type ExtractArrayItem = <T>($ReadOnlyArray<T>) => T;    
type ArrayItemType = $Call<ExtractArrayItem, ArrayType>;

type nestedString = $PropertyType<ArrayItemType, 'something'>; 

const text: nestedString = "TEST";

$Call用于提取数组项类型。

答案 1 :(得分:1)

您实际上可以使用较新的$ElementType以较少的步骤执行此操作(分为与@aleskey-l's answer类似的部分:

type nested = {
 anArray: $ReadOnlyArray<{something: "BLA" | "TEST"}> 
}

type ArrayType = $PropertyType<nested, 'anArray'>;

type ArrayItemType = $ElementType<nested, number>

type nestedString = $PropertyType<ArrayItemType, 'something'>;

const text: nestedString = "TEST";