Type casting an object with JSDoc

Viewed 751

class B extends class A. My factory function returns an object with type A.

The doSomethingWithB function expects and object with type B. If I create a new object with the factory and I'm sure it's type is B, how can I narrow the variable type in JSDoc to tell the IDE that the type is not incompatible? Like casting in Java...

class A {

}

class B extends A {

}

/**
 * @param {string} type
 * @returns {A}
 */
function factory(type) {

    return new factory.types[type]();
}

/**
 * @type {{A: A, B: B}}
 */
factory.types = {
    'A': A,
    'B': B
}

/**
 * @param {B} bObj
 */
function doSomethingWithB(bObj) {
    console.log(bObj);
}

const bObj = factory('B');

doSomethingWithB(bObj);
0 Answers
Related