typescript - 如何在打字稿中调用具有多种类型数组的地图函数
问题描述
我正在开发一个需要遍历 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[]);
解决方案
我认为你可以在这种情况下使用重载,如果你想传递固定元素类型的数组
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'.
推荐阅读
- javascript - 找不到模块'mysql'
- go - 减少 golang 插件文件大小
- java - OpenJDK 1.8 设置/dev/urandom 时哪个配置生效?
- javascript - 网页是否可以在该页面打开时阻止 Windows 进入睡眠模式?
- javascript - ngFor 在 Angular 中制作 5 个 div 和 5 个 uls——而不是内部项目
- mongodb - 查询 MongoDB
- reactjs - 根据数据列表选项重定向到其他页面(Reactjs)
- javascript - 获取可编辑 div 中选定元素的 id
- mysql - Laravel:查询生成器生成器返回与实际 mysql 查询不同的结果
- python - 如何创建用于检查句子相似性的矩阵模板?