I answer to myself, because I like to use Stackoverflow as my personal notebook. If someone has better answers to provide, I'm a buyer!
- Apparently Typescript is a big couchpotato and doesn't follow the type inheritance. Maybe for performance reasons, maybe because the type could be affected by other means and wouldn't be reliable, maybe because it's tricky to do, maybe because it's not yet implemented, maybe because nobody asked for that because they don't use the model object, or Intellisense.
- Didn't see anything clear in the docs/upcoming features of Typescript 2.3 about that. There's a mention about strongly typing
this
here when using the --noImplicitThis
compilation option, and the ThisType<T>
function to declare this
explicitely. But apparently it's more about a function being aware of its embedding structure type, than following the object model flow. And it doesn't help in my case.
- That, I can answer!
Here is a code sample (Test it in Typescript playground):
interface TestInterface {
test: () => {}
}
class Obj implements TestInterface{
test() {
return { test: 'test' }
}
}
class Wrapper<T extends TestInterface, TEST> {
public obj;
constructor(obj: { new (): T; prototype: { test: TEST } }) {
this.obj = new obj();
}
test():TEST {
return this.obj.test();
}
}
let w = new Wrapper(Obj);
let r = w.test();
In this case, r
type is {test: string}
. This solution consists in not instantiating Obj
but getting its prototype to deduce the type.
While searching, I also fell on a simpler way to write it by there (see update 2).
It gives the possibility to keep clever typings and mainly code completion when using some dynamic patterns. Now, it's still a choice to do to choose between completion or a smarter/clearer design...
This sample is based on an example from the Typescript handbook, at the bottom of this page.