Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.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
Arrays typescript是否不检查Array.map结果上的类型?_Arrays_Typescript_Dictionary - Fatal编程技术网

Arrays typescript是否不检查Array.map结果上的类型?

Arrays typescript是否不检查Array.map结果上的类型?,arrays,typescript,dictionary,Arrays,Typescript,Dictionary,给定上述代码,typescript编译器将不允许函数返回不属于该类型的值,但是,如果返回的值来自Array.map,则会返回。您可以通过Typescript上的上述代码段看到这一点: 有人能解释一下这是怎么回事吗?您的map函数没有指定返回类型,因此它可以返回任何内容。如果您想要更严格的检查,您需要明确: interface Company { id: string; name: string; } type input = Company; // This fails as the

给定上述代码,typescript编译器将不允许函数返回不属于该类型的值,但是,如果返回的值来自Array.map,则会返回。您可以通过Typescript上的上述代码段看到这一点:


有人能解释一下这是怎么回事吗?

您的map函数没有指定返回类型,因此它可以返回任何内容。如果您想要更严格的检查,您需要明确:

interface Company {
  id: string;
  name: string;
}

type input = Company;

// This fails as the types don't match
const ACME: input = { id: '123', name: 'ACME', ceo: 'Eric' };

function mapIds(ids: string[]): input[] {
  // This compiles, but it shouldn't, or is Array.map returning something different?
  return ids.map(id => ({ id: '1', name: '1', ceo: 'Eric' }));

  // This fails as types don't match
  return [{ id: '1', name: '2', ceo: 'Eric' }];
}

原因是
.map
函数是一种映射操作,用于将数组中的每个元素转换为新类型。如果不指定,TypeScript不知道新类型是什么

展开下面的评论。TSC对象到行
返回[{id:'1',name:'2',ceo:'Eric'}]input[]
,而它不是。但是
ids.map(id=>({id:'1',name:'1',ceo:'Eric'}))本身是可以的(因为.map可以返回任何类型),然后将其分配给允许的
input[]


感谢@TitianCernicova Dragomir和@p.s.w.g对此的评论。

地图中的返回类型被标识为
{id:string;name:string;ceo:string;}[]
--这很好。我认为问题在于,当您试图将该值作为
输入返回时,tsc为什么不抱怨[
,但当您试图直接返回
[{id:'1',name:'2',ceo:'Eric'}]时,tsc却失败了
?@p.s.w.g,因为TS只会在将对象文本直接分配给预期为特定类型的对象时抱怨过多的属性检查。在本例中,
map
调用是独立键入的,返回类型是类型为
{id:string,name:string,ceo:string}[]
的数组。然后将其分配给类型为
input[]
的数组,这是允许的,并且不允许进行多余的属性检查performed@TitianCernicova-德拉戈米尔解释得很好。我认为要想让答案被认为是完整的,它应该包括这些细节。@p.s.w.g我同意,如果apokryfos愿意,他可以自由地包含该评论的任何部分,他的解决方案与我发布的代码相同,所以我自己不打算添加答案谢谢你的评论。我已经更新了我的答案,希望能涵盖细节。
interface Company {
  id: string;
  name: string;
}

type input = Company;

// This fails as the types don't match
const ACME: input = { id: '123', name: 'ACME', ceo: 'Eric' };

function mapIds(ids: string[]): input[] {
  return ids.map((id):Company => ({ id: '1', name: '1', ceo: 'Eric' }));

  // This fails as types don't match
  return [{ id: '1', name: '2', ceo: 'Eric' }];
}