Have isFormT match on derived form types by walking the prototype chain.
authorRobert Sesek <rsesek@bluestatic.org>
Sun, 19 Jul 2020 21:58:02 +0000 (17:58 -0400)
committerRobert Sesek <rsesek@bluestatic.org>
Sun, 18 Oct 2020 06:36:46 +0000 (02:36 -0400)
src/core/Form.test.ts
src/core/Form.ts

index 4178d1930f11e37ed665c222e1f52e92a3f77ebd..5b00536c05e4553ff7a685be69b6a4bf5fdd6ccd 100644 (file)
@@ -92,3 +92,22 @@ test('form types', () => {
   expect(isFormT(new FormA(), FormB)).toBe(false);
   expect(isFormT(new FormB(), FormB)).toBe(true);
 });
+
+test('derived form types', () => {
+  class Base extends Form<any> {
+    readonly name = 'Base';
+    readonly lines = {};
+  };
+  class Derived extends Base {};
+  class SecondDerived extends Derived {};
+
+  expect(isFormT(new Base(), Base)).toBe(true);
+  expect(isFormT(new Derived(), Derived)).toBe(true);
+
+  expect(isFormT(new Derived(), Base)).toBe(true);
+  expect(isFormT(new Base(), Derived)).toBe(false);
+
+  expect(isFormT(new SecondDerived(), SecondDerived)).toBe(true);
+  expect(isFormT(new SecondDerived(), Derived)).toBe(true);
+  expect(isFormT(new SecondDerived(), Base)).toBe(true);
+});
index dc7e70ac0353f355dee4de6b7fca44e714e9fdc9..6aaece894f34b1ea23065fcccd08f264bceb4f77 100644 (file)
@@ -66,5 +66,9 @@ export type FormClass<T extends Form> = new (...args: any[]) => T;
 export function isFormT<T extends Form>(form: Form,
                                         formClass: FormClass<T>):
                                             form is T {
-  return form.constructor === formClass;
+  for (let proto = form; proto !== null; proto = Object.getPrototypeOf(proto)) {
+    if (proto.constructor === formClass)
+      return true;
+  }
+  return false;
 }