首页 > 解决方案 > How to check if array of class?

问题描述

Let's say I have a class named Form.

export class Form {}

How can I check if a variable is an array of Form?

const foo: Form = new Form()

if (foo instanceof Form) {}

const baz: Form[] = [new Form(), new Form()]

?

标签: typescript

解决方案


You can use Array.prototype.every to check if every single entry in your baz array is indeed an instance of Form:

const baz = [new Form(), new Form()];
console.log(baz.every(entry => entry instanceof Form));  // true

const baz2 = [new Form(), new Form(), ''];
console.log(baz2.every(entry => entry instanceof Form));  // false

See proof-of-concept on TypeScript playground.


推荐阅读