vendredi 19 mai 2023

Is there a simple pattern in Typescript to write a wrapper Class vor some type without explicily copying every attribute? [duplicate]

I often receive raw JSON data from the outer world. (e.g. via http requests) Often this data represents entities I want to do operations on. For this purpose I want to write a wrapper class for some given entity, but without explicitly copying each attribute to the class! Is there a way to do this in a type save manner?

Here is my usecase

// This is a wrapper class
new class User {
 // some unknown implementation
}

interface UserDto {
    readonly id: string;
    readonly friends: string[];
}

const user = new User(userDto);
console.log(user.id);
console.log(user.friendsConut()); // this an extension to UserDto

And here is the implementation for the User class I want to avoid, for the sake of dry code:

class User {
    readonly id: string;
    readonly friends: string[];
    constructor(dto: UserDto){
         this.id = dto.id;
         this.friends: dto.friends;
    }

    frindsCount(){
        return this.friends.length
    }

Aucun commentaire:

Enregistrer un commentaire