How do I represent an arbitrary type of value in Typescript? For example:
class Checker {
/**
* @param first a value
* @param second the type of a value
* @return true if "first" is an instance of type "second"
*/
public instanceOf(first: unknown, second: Class): boolean {
return first instanceof second;
}
}
The above code has to behave the same as first instanceof second
but I can't figure out what type second
must have to make this work.
This question is related to Is there a type for "Class" in Typescript? And does "any" include it? but none of the answers work for classes with private constructors (e.g. LocalDate). I cannot simply change the constructor to public because users must be able to pass in values from third-party libraries.
What doesn't work
new (...args: never[]) => unknown)
fails with:
Cannot assign a 'private' constructor type to a 'public' constructor type.
public instanceOf<T>(first: unknown, second: T)
does not work because it allows users to pass non-type values intosecond
such as1234
or"test"
. Remember, iffirst instanceof 1234
results in a compiler error then so shouldinstanceOf(first, 1234)
.public instanceOf<T extends object>(first: unknown, second: T)
blocks non-type values but then the method implementation fails to compile with:
TS2359: The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.