Constructing an object using a type of a generic?
<p>I'm working with a public RESTful API that returns objects that have fields of URLs that point to more info. I'd like to wrap these fields in an object that indicates what they point to so I created an object like so:</p>

<pre><code>class APIResource&lt;T&gt; {
    url: string;
}
</code></pre>

<p>Where <code>T</code> describes what the <code>url</code> should return. <code>T</code> isn't actually even used by the object as far as typescript is concerned but it helps me know what I should expect. I'm working with Angular2 but please note that what I'm trying to do is not Angular specific. I have an API class where I can request a URL and provide a type to convert it to:</p>

<pre><code>class Person {
  name: string;
  age: number;

  constructor(obj: any) {
    // all Constructable&lt;T&gt; classes will
    // have a constructor that looks
    // exactly like this
    Object.assign(this, obj);
  }

  print() {
    console.log(this.name + ' is ' + this.age);
  }
}

interface Constructable&lt;T&gt; {
  new (obj: any): T;
}

public get&lt;T&gt;(url: string, type: Constructable&lt;T&gt;): Observable&lt;T&gt; {
  return this.http.get(url).map(result =&gt; {
    return new type(result.json());
  });
}
</code></pre>

<p>Basically, I make an ajax request to get json from the API, I pass it through the constructor of my type and return the object. It would be used like this:</p>

<pre><code>var person: Person;
api.get('/person/1/', Person).subscribe(p =&gt; person = p);
</code></pre>

<p>This works if I have the constructor to pass in, but what I'd like to do is write up a <code>getResource&lt;T&gt;(resource: APIResource&lt;T&gt;): Observable&lt;T&gt;</code> function so I could do something like this:</p>

<pre><code>var res: APIResource&lt;Person&gt; = { url: '/person/1/' };
var person: Person;
api.getResource(res).subscribe(p =&gt; person = p);
</code></pre>

<p>But so far nothing has worked. Right now I can't get the type <code>T</code> out of <code>APIResource</code> to use my current method. I've tried modifying APIResource:</p>

<pre><code>class APIResource&lt;T&gt; {
  url: string;

  getType(): T {
    return T;
  }
}
</code></pre>

<p>Or</p>

<pre><code>class APIResource&lt;T extends Constructable&lt;T&gt;&gt; {
  url: string;

  fetch(): T {
    // just a test to see if tsc complains
    // which it does with "cannot find name T"
    var obj: any = {};
    return new T(obj);
  }
}
</code></pre>

<p>But neither of them work. I know the type information is gone once it's javascript. Instead of the type moving around, I think I'd be able to work with moving around the constructor but I don't think I can do that with generics.</p>

<p>Is there anyway to make this work with generics?</p>

<p>I'm using typescript 1.8.7</p>