首页 > 解决方案 > 打字稿无法推断地图循环内的类型

问题描述

我有这些类型:

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 循环内的类型与循环外的类型相同?

标签: typescript

解决方案


推荐阅读