简体   繁体   English

打字稿不检查Array.map结果的类型吗?

[英]Does typescript not check types on the result of an Array.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' }];
}


Given the above code, the typescript compiler will not allow the function to return values that don't belong in the type, however if the return is from an Array.map, it does. 给定上面的代码,typescript编译器将不允许函数返回不属于该类型的值,但是如果返回来自Array.map,则确实如此。 You can see this with the above snippet on the Typescript Playground: https://www.typescriptlang.org/play/ 你可以在Typescript Playground上面的代码片段看到这个: https ://www.typescriptlang.org/play/

Could anyone explain what's up with that? 任何人都能解释一下这是怎么回事?

Your map function does not specify a return type so it can return anything. 您的map函数没有指定返回类型,因此它可以返回任何内容。 If you want a stricter check you need to be explicit: 如果您想要更严格的检查,您需要明确:

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' }];
}

The reason is that the .map function is a mapping operation intended to transform each element in the array to a new type. 原因是.map函数是一个映射操作,旨在将数组中的每个元素转换为新类型。 TypeScript does not know what that new type will be if you don't specify. 如果您未指定,TypeScript不知道该类型是什么。

To expand on the comments below. 扩展以下评论。 TSC objects to line return [{ id: '1', name: '2', ceo: 'Eric' }]; return [{ id: '1', name: '2', ceo: 'Eric' }]; TSC对象return [{ id: '1', name: '2', ceo: 'Eric' }]; because it expects a type of input[] which it is not. 因为它需要一种input[]而不是它。 However ids.map(id => ({ id: '1', name: '1', ceo: 'Eric' })); 但是ids.map(id => ({ id: '1', name: '1', ceo: 'Eric' })); by itself is fine (because .map can return any type) and that is then assigned to input[] which is allowed. 本身很好(因为.map可以返回任何类型),然后将其分配给允许的input[]

Thanks to @TitianCernicova-Dragomir and @pswg for their comments on this. 感谢@ TitianCernicova-Dragomir和@pswg对此的评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM