Suppose we have an interface:
class A {
method(x:number) : string
}
And a function:
const b = (x: string) : number;
Our goal is to test the function against the interface.
Here is one way to achieve this:
type InterfaceKey = {
method: any
};
function typecheck<T, K extends keyof InterfaceKey >(imp: () => T, d: T[K]) {
// K cannot be used to index type T ^
imp();
return d;
}
typecheck(someclass, 555); // <-- type check _is actually works_ here
// or
function typecheck <T>(imp: () => T, d: any) {
imp();
if(!d) {
let mock: T;
mock.default = d; // default does not exists on type T
return mock;
}
return d;
}
It seems that the first approach is the most effective, as it performs a type check in Webstorm (but not in tsc) although it does not compile.
For more information, check out: https://github.com/Microsoft/TypeScript/issues/15768