typescript - 打字稿无法推断地图循环内的类型
问题描述
我有这些类型:
type Someone = {
name: string;
type: Human | Animal;
};
type Human = {
value: "human";
age: number;
friends: string[];
};
type Animal = {
value: "animal";
age: number;
cute: boolean;
};
我有两个基于“某人”类型的变量:
const humanVar: Someone = {
name: "Jimmy",
type: {
value: "human",
age: 15,
friends: ["Patrick", "Anna"]
}
};
const animalVar: Someone = {
name: "Doogie",
type: {
value: "animal",
age: 3,
cute: true
}
};
当您想有条件地使用每种类型属性时,它可以正常工作。但是由于某种原因,打字稿忘记了在地图循环中的类型是什么:
//let's say 'someone' variable is human or animal
switch (someone.type.value) {
case "animal": {
//it works, typescript knows that type is AnimalType
let test1 = someone.type.cute;
break;
}
case "human": {
//it works, typescript knows that type is HumanType
let test2 = someone.type.friends;
const mappedFriends = someone.type.friends.map((friend) => {
//it doesn't work inside map loop, typescript forgets that it should be HumanType
let test3 = someone.type.friends;
return friend;
});
break;
}
}
如何让 Typescript 知道 map 循环内的类型与循环外的类型相同?
解决方案
推荐阅读
- jquery - 如何获取任何 html 属性的动态部分并在 jquery 选择器中使用它?
- ruby-on-rails - 当我尝试在 MAC 终端上运行我的项目时,出现此错误
- arduino - 如何像 Arduino Uno 的按钮一样使用旋转编码器
- typescript - 我如何在groupscore上对这个数组进行排序?
- emacs - 选择算术运算,例如 2 + 2 eval 并在 minibuffer 中回显结果
- java - 即使找到路径,BFS Maze Solver 也会返回 false
- android - 如何将预定通知添加到闹钟应用程序 - Flutter
- javascript - 如何在 window.onload 事件后使用 reactjs / nextjs 加载脚本
- python - Pandas 将两个 DataFrame 中单元格中的字符串与规则进行比较
- r - assign(x)、eval(parse(text = "x"))、get(x) 和 deparse(substitute(x)) 有什么区别?