如何在TypeScript中检查对象类型

4
我有一个包含两种不同对象的JSON文件。我想根据它们的类型迭代JSON。为了说明我的问题,我创建了两种不同类型的对象AnimalPerson
现在我想检查对象的类型,无论它是动物还是人。
type Animal = {
  name: string;
  legs: number;
}

type Person = {
  name: number;

}

const checkType = (isAnimalOrPerson: Animal | Person) =>{
  if(isAnimalOrPerson instanceof Animal){
     console.log("animal type");
  }
  else{

  }
}

如果条件为"Animal" only refers to a type, but is being used as a value here.,我会得到一个错误。


Animal 是一种类型,而不是一个类。这就是为什么不能使用 instanceof 的原因。 - user13258211
请参考以下链接:https://www.georgestefanis.com/blog/2020/10/30/typescript-how-to-check-for-types.-using-tagged-unions/. 该链接涉及 TypeScript 中如何使用标记联合检查类型。 - Tushar Wason
https://github.com/Microsoft/TypeScript/wiki/FAQ#what-is-type-erasure - VLAZ
3个回答

1

type存在的问题在于它仅在开发期间存在;一旦你进行转译,它就会消失,TypeScript无法预见你可能传递的运行时值的形状(除非你进行断言,即对对象拥有的属性进行明确的检查)。如果你想进行类型检查,你必须用另一种方式来实现,例如使用类,然后这种方法只有在你实际实例化类时才能起作用(而不仅仅是将其用作形状):

class Animal {
    name: string;
    age: number;
    legs: number;
}

class Person {
    name: string;
    age: number;
    job: string;
    education: string;
}

let a: Animal = new Animal();
let b: Animal = { name: "Rex", legs: 4, age: 3 };
let c = new Person();

function checkType(arg: Animal | Person): string {
    if (arg instanceof Animal) {
        return "This is an animal";
    } else if (arg instanceof Person) {
        return "This is a person";
    }

    return "Can't tell";
}

console.log(checkType(a)); // This is an animal
console.log(checkType(b)); // Can't tell
console.log(checkType(c)); // This is a person

这种方法的问题在于它只会在使用该类创建对象时返回true,但在我的情况下,我有一个JSON并对其进行迭代。 - Saghar Francis


0

有多种方法可以检查PersonorAnimal值是否也满足Animal

  1. 通过属性强制转换
if ('legs' in toBeDetermined) {
  // toBeDetermined should be `Animal` in this block
}

2. 给 Animal 分配一个 唯一的符号 并检查它们。
const animalTag: unique symbol = Symbol("Animal tag");

type Animal = {
  __brand__: typeof animalTag;
  name: string;
  legs: number;
}

if (toBeDetermined.__brand__ === animalTag) {
  // toBeDetermined can be coerced manually into Animal
}

我更喜欢1,因为动物具有不相交属性


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接