检查变量属于两个枚举中的哪一个

问题描述 投票:0回答:1

我有 2 个枚举和一个变量。 该变量包含一个对象数组。 其中一个 props 包含其中一个枚举的值。 我需要检查哪个枚举拥有对象类型的值。

我有类似的东西:

enum Animal {
  CAT = 'cat',
  DOG = 'dog',
}

enum Bird {
  RAVEN = 'raven',
  PIGEON = 'pigeon',
}

const creatureList: Array<{
  type: Animal | Bird ;
  name: string;
}> = [
  {
    type: 'cat',
    name: 'Mauricio',
  },
  {
    type: 'raven',
    name: 'Jacob',
  },
]

我需要这样的东西:

function isAnimal(type: Animal | Bird): type is Animal {
  return Object.values(Animal).includes(type);
}

function isBird(type: Animal | Bird): type is Bird {
  return Object.values(Bird).includes(type);
}

creatureList.forEach((creature) => {
  // do something

  if (isAnimal(creature.type)) {
    // do something for animals
  }

  if (isBird(creature.type)) {
    // do something for birds
  }

  // do something else
});

但是当我尝试这样做时,我收到错误:

TS2345:“动物 | ”类型的参数“鸟”不可分配给“动物”类型的参数。类型“Bird.RAVEN”不可分配给类型“Animal”。

上线

  return Object.values(Animal).includes(type);

如何正确检查某个值属于哪个枚举?

typescript types enums
1个回答
0
投票

您的问题是

creatureList
中的类型不是您的枚举类型。打字稿中的枚举的行为与其他类型不同。您需要用赋值替换该值。

const creatureList: Array<{
  type: Animal | Bird ;
  name: string;
}> = [
  {
    type:  Animal.CAT,
    name: 'Mauricio',
  },
  {
    type: Animal.DOG,
    name: 'Jacob',
  },
]
© www.soinside.com 2019 - 2024. All rights reserved.