Get property from generic class instance with type safety

45 Views Asked by At

It's easy enough if the type doesn't matter, but I was hoping to retain the type being returned. I tried this, but it just says the getData() function returns 'unknown'.

Simplified example:

class DataHolder<DataType> {
  data: DataType;
  constructor(data: DataType) {
    this.data = data;
  }
}

function getData<U, T extends DataHolder<U>>(holder: T) {
  return holder.data;
}

let x = getData(new DataHolder<number>(10));
let y = x * 3; // error x is unknown
1

There are 1 best solutions below

0
On BEST ANSWER

You'e using too many generics. getData is polymorphic only in one way, therefore it needs only one generic.

function getData<T>(holder: DataHolder<T>): T {
  return holder.data;
}

Alternatively:

function getData<T extends DataHolder<any>>(holder: T): T['data'] {
  return holder.data;
}

Both will work as expected.