问题
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