Home > Software engineering >  Convert the Normal class to generic in typescript
Convert the Normal class to generic in typescript

Time:06-16

I have a class to get JSON objects and convert them to the class that I want. the code is below.


import {plainToClass} from "class-transformer";
import UserDto from "../../auth/dto/user.dto";

class ConvertJson {
    
    userData(data) {
        return plainToClass(UserDto, data);
    }
}

when I want to convert the class to generaic class


import {plainToClass} from "class-transformer";
import UserDto from "../../auth/dto/user.dto";

class ConvertJson<T> {

    userData(data) {
        return plainToClass(T, data);
    }
}

I get this error

T only refers to a type, but is being used as a value here

CodePudding user response:

After tweaking the code I found out that typescript generic is very different from C# or other languages so I convert the code to this so it has a generic vibe but not syntax.


import {plainToClass} from "class-transformer";

interface IClass {
    new (...args : any[])
}

class ConvertJson {

    constructor(private dto : IClass) {
    }

    userData(data) {
        return plainToClass(this.dto, data);
    }
}


the reason I use IClass instead of any is that I want to make sure other teammates use class, not other types.

CodePudding user response:

I guess want you want to do is cast the output according to the input type

class ConvertJson<T> {
    userData(data) {
        return <T>plainToClass(data);
    }
}
  • Related