sfaust
sfaust

Reputation: 2373

json2typescript convert to type T

I am using json2typescript in Angular and trying to create a general function to convert. Right now I have it working with something like this:

  private ConvertBaseToRole(baseObject: any): Role {
    const jsonConvert: JsonConvert = new JsonConvert();
    jsonConvert.operationMode = Constants.ConverterMode;
    return jsonConvert.deserializeObject<Role>(baseObject, Role);
  }

This is fine but I have to create the same thing from every class I want to convert. Instead I would like to do this as a generic function that can be used with any class:

export function ConvertBaseToObject<T>(baseObject: any): T {
  const jsonConvert: JsonConvert = new JsonConvert();
  jsonConvert.operationMode = Constants.ConverterMode;
  return jsonConvert.deserializeObject<T>(baseObject, T);
}

However it's giving me a compiler error 'T' only refers to a type, but is being used as a value here.. How do I get the right value to use from the type T that is passed?

Upvotes: 0

Views: 342

Answers (1)

Rafi Henig
Rafi Henig

Reputation: 6432

Keep in mind that Typescript generics only exist at compile time so you cannot use type-argument to instantiate types;

However your expected behavior could still be achieved as demonstrated below:

export function ConvertBaseToObject<T>(baseObject: any, toType: { new(): T }): T {
  const jsonConvert: JsonConvert = new JsonConvert();
  jsonConvert.operationMode = Constants.ConverterMode;
  return jsonConvert.deserializeObject<T>(baseObject, toType);
}

Upvotes: 2

Related Questions