Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript Can';不容易迭代联合类型的共享数组属性_Typescript - Fatal编程技术网

Typescript Can';不容易迭代联合类型的共享数组属性

Typescript Can';不容易迭代联合类型的共享数组属性,typescript,Typescript,我正在构建一个使用递归数据类型的嵌套文件夹UI interface TreeRoot{kind:“root”,子级:TreeBranch[];} 接口TreeBranch{kind:“branch”,子级:TreeLeaf[];} 接口TreeLeaf{kind:“leaf”,子级:未定义;} 类型All=TreeRoot | TreeBranch | TreeLeaf; 鉴于上述结构,我认为这是可能的: /**声明(但不定义)变量'example',用于说明目的*/ 声明常量示例:All;

我正在构建一个使用递归数据类型的嵌套文件夹UI

interface TreeRoot{kind:“root”,子级:TreeBranch[];}
接口TreeBranch{kind:“branch”,子级:TreeLeaf[];}
接口TreeLeaf{kind:“leaf”,子级:未定义;}
类型All=TreeRoot | TreeBranch | TreeLeaf;
鉴于上述结构,我认为这是可能的:

/**声明(但不定义)变量'example',用于说明目的*/
声明常量示例:All;
(例如.children | |[]).map(x=>{
console.dir(x);
});
但是,上面的代码无效。它发出以下错误:

This expression is not callable.
  Each member of the union type
  ' (<U>(callbackfn: (value: TreeBranch, index: number, array: TreeBranch[]) => U, thisArg?: any) => U[])
  | (<U>(callbackfn: (value: TreeLeaf, index: number, array: TreeLeaf[]) => U, thisArg?: any) => U[])'
  has signatures, but none of those signatures are compatible with each other.ts(2349)
此表达式不可调用。
联合类型的每个成员
“((callbackfn:(值:TreeBranch,索引:number,数组:TreeBranch[])=>U,thisArg?:any=>U[]))
|((callbackfn:(值:TreeLeaf,索引:number,数组:TreeLeaf[])=>U,thisArg?:any=>U[])”
具有签名,但这些签名都不相互兼容。ts(2349)
`


为什么这些签名彼此都不兼容?我能做些什么来简化迭代?

函数类型的联合是可调用的,因为,但仍然存在:您只能调用它,因为大多数函数都是重载的或泛型的。因为
Array.map
Array.map
都是通用的,所以不能这样做。幸运的是,您可以在映射之前将
A[]|B[]
扩展到
(A | B)[
,这通常是很好的,因为在调用
map()
时,“要么是全部
A
s,要么是全部
B
的数组”和“每个元素都是
A
B
的数组”之间的区别实际上并不重要:

所以你想用

((example.children || []) as (TreeBranch | TreeLeaf)[]).map(x => {
  console.dir(x);
});
或者更安全的类型

const children: Array<TreeBranch | TreeLeaf> = example.children || [];
children.map(x => console.dir(x));
const children:Array=example.children | |[];
children.map(x=>console.dir(x));

这一点包含在本次重复的问题中。祝你好运