TypeScript 中使用 instanceof 判断对象是否实现接口
在 TypeScript 中,可以使用 'instanceof' 运算符来判断一个对象是否实现了某个接口。例如:
interface Person {
name: string;
age: number;
}
class Student implements Person {
name: string;
age: number;
grade: number;
constructor(name: string, age: number, grade: number) {
this.name = name;
this.age = age;
this.grade = grade;
}
}
const person: Person = new Student('Alice', 18, 12);
if (person instanceof Student) {
console.log('person is a Student');
} else {
console.log('person is not a Student');
}
上面的代码中,我们定义了一个 'Person' 接口,然后定义了一个 'Student' 类,该类实现了 'Person' 接口。我们创建了一个 'person' 对象,其类型为 'Person',实际上是一个 'Student' 实例。我们使用 'instanceof' 运算符来判断 'person' 是否是 'Student' 类型的实例,如果是,则输出 'person is a Student',否则输出 'person is not a Student'。
原文地址: https://www.cveoy.top/t/topic/lL4x 著作权归作者所有。请勿转载和采集!