首页 > 解决方案 > 如何在打字稿中调用具有多种类型数组的地图函数

问题描述

我正在开发一个需要遍历 type 数组的 Typescript 函数Employee[] | Guest[]。问题是 TypeScript 正在发出错误TS2349: This expression is not callable... has signatures but none of those are compatible with each other。我期望能够迭代数组,并且只需要在使用局部变量之前使用类型保护,但事实并非如此。有没有一种方法可以使用该map功能而无需创建自定义类型?该函数只需要遍历这两种类型,所以我希望将参数的类型定义保持为Employee[] | Guest[]. 下面是一个简单的示例,其中people.map.

interface Employee {
  id: string;
  firstName: string;
}

interface Guest {
  firstName: string;
}

function getFirstNames(people: Employee[] | Guest[]): string[] {
  return people.map((x: Employee | Guest) => {
    return x.firstName;
  });
}

const employeeFirstNames = getFirstNames([
  {id: '1', firstName: 'Steve'},
  {id: '2', firstName: 'James'},
] as Employee[]);

const guestFirstNames = getFirstNames([
  {firstName: 'Mary'},
] as Guest[]);

标签: typescript

解决方案


我认为你可以在这种情况下使用重载,如果你想传递固定元素类型的数组

function getFirstNames(people: Employee[]): string[];
function getFirstNames(people: Guest[]): string[];
function getFirstNames(people: (Employee | Guest)[]): string[] {
  return people.map((x: Employee | Guest) => {
    return x.firstName;
  });
}

在这种情况下,你不会担心公共接口,所以像下面这样的混合类型会报错

const guestFirstNames = getFirstNames([
   { id: '1', firstName: 'Steve' },
  { firstName: 'Mary' }
]); // <-- No overload matches this call. Overload 1 of 2, '(people: Employee[]): string[]', gave the following error. Property 'id' is missing in type '{ firstName: string; }' but required in type 'Employee'. Overload 2 of 2, '(people: Guest[]): string[]', gave the following error. Type '{ id: string; firstName: string; }' is not assignable to type 'Guest'. Object literal may only specify known properties, and 'id' does not exist in type 'Guest'.

推荐阅读