Generic to assess if a parameter is “instanceof a generic class” if constructor is private

最后都变了- 提交于 2021-01-05 09:11:40

问题


I am trying to assert in a function if an object is instance of a class with type predicate.

function assertClass<CL extends new (...args: any[]) => any>(v: any, theClass: CL, message: string): v is CL
{
    let is = v instanceof theClass ;
    assert(is, message);
    return is;
}

(credit)

And it works except when the constructor of the class is private

class Cat{}
class Dog{
    private constructor(){
    }
    static async build(){
        let ret = new Dog(); 
        await somethingElse(); 
        return ret;
    }
}
let animal: Cat | Dog;
async function createAnimal(){ if (new Date().getTime() % 2) return new Cat(); else await Dog.build();}
animal= createAnimal();
assertClass(animal, Cat, 'should be a Cat');
assertClass(animal, Dog, 'should be a Cat');  // Cannot assign a 'private' constructor type to a 'public' constructor type

Is there a way to overcome this?

来源:https://stackoverflow.com/questions/64792340/generic-to-assess-if-a-parameter-is-instanceof-a-generic-class-if-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!