我正在开发一个需要迭代 Employee[] | Guest[]
类型数组的 Typescript 函数。问题是 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[]);
答案 0 :(得分:0)
将数组输入为 Employee
和 Guest
的并集。
function getFirstNames(people: (Employee | Guest)[]): string[] {
return people.map((x: Employee | Guest) => x.firstName);
}
答案 1 :(得分:0)
我认为在这种情况下你可以使用重载,如果你想传递具有固定元素类型的数组
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'.