I'm quite new to Typescript and struggling with a, what seems to be, easy problem in Typescript (I come from C++, so generics/templates shouldn't be an issue to understand). I'm constantly struggling quite a lot with type checking in Typescript. I keep thinking I understand it, but then don't I when I need it. I've been searching, but a lot of methods don't seem to do what I want to do as I feel like it's to specific.
I have a generic interface with some (optional) properties. One of these properties is the type of the generic (code is shown below). Next to that I have a generic Angular Service with some methods. These methods use that interface in their argument list. Now, one of these functions have to check the if the argument type that is received in the argument list is exactly the same as the type of the generic type of the Angular Service.
I don't know if this all makes sense, but here's what I explained, but then in code:
interface MyInterface<T> {
command: string;
channel: string;
data?: T;
};
interface MyClass {
url: string;
params?: string[]
};
@Injectable({...})
class MyService<T> implements MyServiceParent<T> {
...
match(obj : MyInterface<T>): boolean {
// check if obj is of type MyInterface<MyClass>
}
};
The thing is, I may be able to check this on build time, but this check must happen during runtime as 'T' of MyInterface
can be anything even if MyService
's generic is MyClass
. The compiler/builder can't check its type as the data that is passed into MyService::match
will come from a post message (the app is in an iframe). This means that I can post a message with, for example, a string and Typescript will compile fine as the data isn't predefined. This is exactly why I need to check for the type during runtime, because this service can only handle that specific type (in this case: MyInterface<MyClass>
).
I hope it's clear. Please ask if something isn't clear.
Thanks for your time!
UPDATE
A code playground for this problem can be found in the following Typescript playground