There's a function I use in testing:
export function cast<T>(obj: any, klass: new (...args: any[]) => T): T {
if (!(obj instanceof klass)) {
throw new Error(`Not an instance of ${klass.name}: ${obj.constructor.name}`);
}
return obj;
}
which is used like this.
interface I {...}
class C implements I {...};
const i: I = ...;
const c = cast(i, C);
However, if I try to use generics, the compiler complains string in the call.
interface I<T> {...}
class C<T> implements I {...};
const i: I<string> = ...;
const c = cast(i, C<string>);
~~~~~~
Type 'any' has no signatures for which the type argument list is applicable. ts(2635)
Any thoughts on how I can make a version of cast that is friendly to generics? Even if it can't verify that instances in i are of type string, finding a way to get it to compile would be useful (otherwise I have to use as anyway.)
TypeScript cast type using generics and constructor? looks close, but seems bound to a specific type hierarchy.