Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  125] [ 6]  / answers: 1 / hits: 16949  / 7 Years ago, tue, january 9, 2018, 12:00:00

Assume that I have an object containing some data. I want to build a generic mapper (only a function respectively - I don't want to instantiate a new class all the time) for all types to use like this: this.responseMapper.map<CommentDTO>(data);



It should simply take all properties from the given type and map the data to it.
What I tried so far:



public map<T>(values: any): T {
const instance = new T();

return Object.keys(instance).reduce((acc, key) => {
acc[key] = values[key];
return acc;
}, {}) as T;
}


new T(); will throw an error: 'T' only refers to a type, but is being used as a value here.



What's the correct way to do this?


More From » class

 Answers
29

You need to pass the type constructor to the method. Typescript erases generics at runtime to T is not known at runtime. Also I would tighten values a bti to only allow memebers of T to be passed in. This can be done with Partial<T>



public map<T>(values: Partial<T>, ctor: new () => T): T {
const instance = new ctor();

return Object.keys(instance).reduce((acc, key) => {
acc[key] = values[key];
return acc;
}, {}) as T;
}


Usage:



class Data {
x: number = 0; // If we don't initialize the function will not work as keys will not return x
}

mapper.map({ x: 0 }, Data)

[#55506] Saturday, January 6, 2018, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jayla

Total Points: 14
Total Questions: 96
Total Answers: 123

Location: Greenland
Member since Fri, Jul 31, 2020
4 Years ago
jayla questions
;