Skip to main content

Class Lineage

ClassLineage - Inheritance Util

ClassLineage.of fetches top-down inheritance chain of given class instance or class itself.

import { ClassLineage } from 'ts-basis';

class A {}
class B extends A {}
...
class Z extends Y {}

const a = new A();
const b = new B();

// Class itself
ClassLineage.of(A); // [A]
ClassLineage.of(B); // [A, B]
// Or its class instances
ClassLineage.of(a); // [A]
ClassLineage.of(b); // [A, B]

ClassLineage.namesOf(B); // ['A', 'B']
ClassLineage.namesOf(b); // ['A', 'B']

// Parent of
ClassLineage.parentOf(B); // A
ClassLineage.parentNameOf(B); // 'A'
ClassLineage.parentOf(A); // null; A doesn't extend from anything
ClassLineage.parentNameOf(A); // null

// Bottom-up order
ClassLineage.of(Z, false); // [Z, Y, ..., A]
ClassLineage.namesOf(Z, false); // ['Z', 'Y', ..., 'A']

// Ancestry
ClassLineage.lastCommonAncestor(A, B); // A
ClassLineage.commonAncestorInfo(A, B); // { commonAncestors: [ A ], lastCommonAncestor: A, senior: A, junior: B, distance: 1, travel: 0, levelCompare: 1, levelDifference: 1 }
class Unrelated {}
ClassLineage.commonAncestorInfo(A, Unrelated); // { commonAncestors: [], lastCommonAncestor: null, senior: null, junior: null, distance: Infinity, travel: Infinity, levelCompare: NaN, levelDifference: NaN }
class B2 extends A {}
ClassLineage.areRelated(B, B2); // true; common parent A
ClassLineage.areRelated(B, Unrelated); // false; no common ancestor

Performance: all ClassLineage methods are about 10M/s; results are auto-cached since types don't generally change during runtime. To turn it off, set ClassLineage.noCache to true.